0

我有一些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 ");

我想让查询的 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')";
}

我将 $m 放入查询中,但它不起作用:

WHERE
      Product = '$id'
      '$m'

任何建议将不胜感激。

4

3 回答 3

2

您应该使用ORoperator 而不是AND,或者更好地使用IN语句。因为我猜 model 不能同时等于a and b,这是不可能的所以你的部分代码应该是这样的:

$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 ");
于 2013-10-29T12:52:48.880 回答
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 ");
于 2013-10-29T12:47:59.877 回答
0

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

    $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");
于 2013-10-29T12:58:34.177 回答