How do you use IN clauses with mysqli prepared statements(你如何在 mysqli 准备好的语句中使用 IN 子句)
问题描述
我正在使用准备好的语句将一些旧代码移至新的 msqli 接口,我在处理包含 IN 子句的 SQL 语句时遇到问题.我通常会这样做:
I’m moving some old code over to the new msqli interface using prepared statements, I’m having trouble with SQL statements containing the IN clause. I would just normally do this:
$ids = '123,535,345,567,878'
$sql = "SELECT * FROM table WHERE id IN ($ids)";
$res = mysql_query($sql);
将其转换为 mysqli 和准备好的语句我尝试了多种解决方案:
Converting this to mysqli and prepared statements I have tried a number of solutions:
$ids = '123,535,345,567,878'
$ids = implode($ids,',');
$result = $msqli->prepare("SELECT foo,blar FROM table WHERE id IN (?));
$result->bind_param("i", $ids);
$result->execute();
以上失败,计算数组中的元素数和更改 SQL 字符串中问号的数量以及为数组中的每个元素调用 bind_parm 也失败.仅使用逗号分隔的字符串也会失败.
The above fails and calculating the number of elements in the array and altering number of question marks in the SQL string and calling bind_parm for each element in the array also fails. Just using the comma separated string also fails.
我在 Google 上找不到关于此的好的文档,那么您是如何解决这个问题的?
I can find no good documentation in Google on this, so how have you solved the problem?
推荐答案
看这里之前有人问过的一个类似问题的答案(第二个代码示例):
Look at the answer to a similar question that has been asked here before (second code sample):
我有一个整数数组,如何在 mysql 查询中使用每个整数(在 php 中)?
归结为:
- 创建带有适量问号的 SQL 字符串
- 使用
call_user_func_array()
将数组绑定到查询字符串
- create the SQL string with the right amount of question marks
- use
call_user_func_array()
to bind your array to the query string
这篇关于你如何在 mysqli 准备好的语句中使用 IN 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你如何在 mysqli 准备好的语句中使用 IN 子句


基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在多维数组中查找最大值 2021-01-01