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

查看:98
本文介绍了如何在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):

I have an array of integers, how do I use each one in a mysql query (in 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天全站免登陆