将 PHP 中的预准备语句与 SQL 中的 IN 函数结合使用
我正在开发一个使用 3 个表(标准化)的标记系统。我想创建一个准备好的声明,当某些人搜索“红苹果”时,它会显示所有标记为“红”和“苹果”的项目。
目前我的查询看起来像这样:
$stmt = $db->prepare("SELECT co.content_id, co.description FROM em_content AS co LEFT JOIN em_contenttags AS ct ON co.content_id = ct.content_id LEFT JOIN em_tags AS ta ON ct.tag_id = ta.tag_id WHERE ta.tag IN (?)");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
我尝试将 $query
制作为数组并使用占位符作为“?”在查询中和 bind_param
变量中的“s”,但我无法将 $query
作为数组传递,否则会引发错误。
有什么办法可以通过准备好的语句来完成这项工作吗?
仅供参考,我没有使用 PDO,我使用的是 mysqli
I'm working on a tagging system using 3 tables (normalised). I wanted to create a prepared statement for when some searches for example "red apples", that it brings up all the items which have been tagged "red" and "apples".
Currently my query looks something like this:
$stmt = $db->prepare("SELECT co.content_id, co.description FROM em_content AS co LEFT JOIN em_contenttags AS ct ON co.content_id = ct.content_id LEFT JOIN em_tags AS ta ON ct.tag_id = ta.tag_id WHERE ta.tag IN (?)");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
I've tried making $query
an array and using placeholders for the "?" in the query and "s" in the bind_param
variable, but I can't pass the $query
as an array otherwise it throws an error.
Is there any way to make this work with prepared statements?
Just FYI, I'm not using PDO, I'm using mysqli
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须动态构建占位符,因此数组的每个元素都将有一个
?
:此处不 100% 确定如何使用 MySQLi 的
bind
机制,以上适用于 PDO。You'll have to build up the placeholders dynamically, so you'll have one
?
for each element of the array:Not 100% sure how to use MySQLi's
bind
mechanism here, the above works for PDO.据我所知,不能在“IN()”中使用占位符。您需要连接查询的该部分。
As far as I know, you can't use placeholders inside "IN()". You need to concatenate that part of the query.