这个SQL IF语句有什么问题?

时间:2014-03-28 16:47:47

标签: php mysql if-statement

所以我正在构建一个搜索脚本并且需要传递两个变量,但首先我想确保SQL Query是正确的,所以我现在正在对变量进行硬编码。所以我的变量是

$comma_separated = "'Alberta','Ontario'";

这会传递给查询,如下所示:

$sql = "SELECT * FROM persons WHERE 1=1";



if ($firstname)
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";

if ($surname)
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";

if ($province)
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' WHERE province IN ($comma_separated)";

$sql .= " ORDER BY surname";

然后当查询运行时,我收到此消息:

cannot run the query because: You have an error in your SQL syntax; check the manual that    corresponds to your MySQL server version for the right syntax to use near 'WHERE province IN ('Alberta','Ontario') ORDER BY surname LIMIT 0, 5' at line 1

但对我来说,查询看起来正确,我在这里缺少什么?

提前致谢。

3 个答案:

答案 0 :(得分:2)

你不能在那里WHERE两次。您似乎也尝试以两种不同的方式过滤省值。基于$province始终是值数组(即使只给出一个值)的假设,您可以尝试这样做:

$sql = "SELECT * FROM persons WHERE 1=1";

if (!empty($firstname)) {
    $sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
}

if (!empty($surname)) {
    $sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
}

if (!empty($province)) {
    array_walk($province, function($value, $key_not_used) use ($mysqli) {
        return mysqli_real_escape_string($mysqli, $value);
    });
    $sql .= " AND province IN ('" . implode(',', $province) . "')";
}

$sql .= " ORDER BY surname";

答案 1 :(得分:1)

您的SQL包含两个WHERE

SELECT * FROM persons WHERE 1=1
                      AND firstname='fn'
                      AND surname='sn'
                      AND province='p'
                      WHERE province IN ($comma_separated)
                      ORDER BY surname

将最后一位更改为:

$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' AND province IN ($comma_separated)";

哪个成为:

AND province='p'
AND province IN ('Alberta','Ontario')

答案 2 :(得分:-1)

将最后一部分更改为:

if ($province)
  $sql .= " AND province IN (" . mysqli_real_escape_string($mysqli,$comma_separated) . ")";