用AND动态sql查询php

时间:2013-10-29 12:42:03

标签: php sql

我有一些sql代码:

    $id = "2000";
    $model = $_GET["model"]

    $result = mysql_query("SELECT
    Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
    count(Base.Data.Data_ID) As `U_Count`
    FROM
        Base.Data
    WHERE
        Product = '$id'
        AND model in ('a','b','c')
    GROUP BY ");

我想让查询的一部分是动态的。像这样:

$m= $model;
switch ($m)
{
    case "basic":
        $m = "AND model in ('a','b','c')";
        break;

    case "upgrade":
        $m = "AND model in ('d','e','f')";
        break;

    default:
        $m = "AND model in ('a','b','c')";
}

我在查询中放了$ m,但它不起作用:

WHERE
      Product = '$id'
      '$m'

任何建议都将受到赞赏。

3 个答案:

答案 0 :(得分:2)

您应该使用OR运算符而不是AND,或者更好地使用IN语句。 因为我猜模型不能同时等于ab,所以这是不可能的 因此,部分代码应如下所示:

$m = " AND model in ('a','b','c')";

修改 您可以简化代码:

$id = "2000";
$model = $_GET["model"]



$m= $model;
switch ($m)
{
    case "upgrade":
    $mIN = "'d','e','c'";
        break;

    case "basic":
    default:
    $mIN = "'a','b','c'";
        break;
}


$result = mysql_query("SELECT
Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
count(Base.Data.Data_ID) As `U_Count`
FROM
    Base.Data
WHERE
    Product = '$id'
    AND model in ($mIn)
GROUP BY ");

答案 1 :(得分:1)

删除$ m周围的报价。另外,添加空格并用正确的条件替换AND:

$m= $model;
switch ($m)
{
    case "basic":
        $m = " AND model in ('a','b','c') ";
        break;

    case "upgrade":
        $m = " AND model in ('d','e','f') ";
        break;

    default:
        $m = " AND model in ('a','b','c') ";
}

然后做:

$result = mysql_query("SELECT
Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
count(Base.Data.Data_ID) As `U_Count`
FROM
    Base.Data
WHERE
    Product = '$id'
    $m ");

答案 2 :(得分:0)

您还可以在传递SQL之前将其创建为字符串。如果还可以在运行之前更轻松地调试查询。

    $querytop = "SELECT
        Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
        count(Base.Data.Data_ID) As `U_Count`
        FROM
            Base.Data
        WHERE
            Product = '$id'";

    $m= $model;
    switch ($m)
    {
        case "basic":
            $m = " AND model = 'a'
        AND model = 'b'
        AND model = 'c' ";
            break;

        case "upgrade":
            $m = " AND model = 'd'
        AND model = 'e'
        AND model = 'f' ";
            break;

        default:
            $m = " AND model = 'a'
        AND model = 'b'
        AND model = 'c' ";
    }        
    $sqlquery = $querytop . $m;
    $result = mysql_query("$sqlquery");