微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – mySQL bind_param与IN(?)

在我的所有查询中使用bind_param,我现在想要使用IN(?),其中列表中的元素数量可以变化.

在这里使用的sqlout函数基本上是$sql_db-> prepare, – > bind_param, – > execute(), – > store_result(), – > bind_result

// the code below does not work as the query only matches on element 'a':
$locations = ('a','b','c','d','e');

sqlout ("SELECT Name FROM Users WHERE Locations IN (?)",
    array('s', $locations), array(&$usrName));


// the code below does work as a brute-force method,
// but is not a viable solution as I can't anticipate the number of elements in $locations going forward:

sqlout ("SELECT Name FROM Users WHERE Locations IN (?,?,?,?,?)",
    array('sssss', $locations[0],$locations[1],$locations[2],$locations[3],$locations[4]), array(&$usrName));

有没有人想出更优雅的解决方案呢?

解决方法:

这是一个占位符落在他们脸上的地方.减去自动转义,它们几乎只是内部的字符串替换操作,这意味着如果你有WHERE x IN(?),并传入1,2,3,4,你将得到相当于

WHERE x IN ('1,2,3,4')  // note, it's a string, not individual comma-separated ints

在逻辑上相当于

WHERE x = '1,2,3,4' // again, just a string

而不是更多的预期

WHERE (x = 1) or (x = 2) or (x = 3) or (x = 4)

唯一可行的解​​决方案是建立自己的?列表,例如:

$placeholders = implode(array_fill(0, count($values), '?'));
$sql = "SELECT ... WHERE x IN ($placeholders)";

然后绑定你的参数是很平常的.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐