你如何在 mysqli 准备好的语句中使用 IN 子句

How do you use IN clauses with mysqli prepared statements(你如何在 mysqli 准备好的语句中使用 IN 子句)
本文介绍了你如何在 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 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?(警告:mysqli_query() 需要至少 2 个参数,1 个给定.什么?)
INSERT query produces quot;Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean givenquot;(INSERT 查询产生“警告:mysqli_num_rows() 期望参数 1 为 mysqli_result,给出布尔值;)
prepared statements - are they necessary(准备好的陈述 - 它们是否必要)
Do I need to escape my variables if I use MySQLi prepared statements?(如果我使用 MySQLi 准备好的语句,是否需要转义我的变量?)
Properly Escaping with MySQLI | query over prepared statements(使用 MySQLI 正确转义 |查询准备好的语句)
Is it possible to use mysqli_fetch_object with a prepared statement(是否可以将 mysqli_fetch_object 与准备好的语句一起使用)