duanba8173 2014-03-28 16:47
浏览 74
已采纳

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

so I am building a search script and meed to pass on two variables, but first I want to make sure that the SQL QUery is correct so I am hard-coding the variable for now. So my variable is

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

This is getting passed through to the query, which looks like this:

$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";

and then when the query runs, I get this message:

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

But to me the query looks right, what am I missing here?

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • dongzanxun2790 2014-03-28 16:54
    关注

    You can't have WHERE in there twice. You also seem to be trying to filter on province values in two different ways. Based on the assumption that $province will always be an array of values (even if only a single value is given), you can try this:

    $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";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器