你如何在 mysqli 准备好的语句中使用 IN 子句 [英] How do you use IN clauses with mysqli prepared statements

查看:33
本文介绍了你如何在 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 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆