简体   繁体   English

SELECT查询不适用于使用预准备语句的IN

[英]SELECT query not working with IN using prepared statement

Can someone help me get the SELECT query (2). 有人可以帮我得到SELECT查询(2)。 below to work? 在下面工作?

This string used for both SELECT statements: 此字符串用于两个SELECT语句:

$seller_items = ('6','9','12','13','14','15','16','17','18','19','20','22','23','24','25','26','28','27','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','53','54','55','57','58','59','60','62','63','64','65','61','67','56','69','70','74','73','75','78','80','76','72','95','94','101','102','71','103','2','104','4','81','21','10','11','3','79','5','8','7','97','93','96','98');

(1). (1)。 This SELECT query is working fine: 此SELECT查询工作正常:

if ($stmt = $mysqli->prepare("SELECT info FROM items WHERE item_id IN $seller_items AND active = ?")){
$stmt->bind_param("s",$active); 

(2). (2)。 This SELECT query is not working: 此SELECT查询无效:

if ($stmt = $mysqli->prepare("SELECT info FROM items WHERE item_id IN ? AND active = ?")){
$stmt->bind_param("ss",$seller_items,$active);

I think placing the variable in the SELECT query itself may defeat the purpose of a prepared statement. 我认为将变量放在SELECT查询本身中可能会破坏准备语句的目的。

I can get the IN predicate to work just fine with a non-prepared statement. 我可以使IN谓词与未准备好的语句一起正常工作。 It's the prepared statement with which I am having the problem. 这是我有问题的准备好的声明。

Thank you in advance. 先感谢您。

As @Dai mentioned the IN cannot be parameterized with just one variable. 正如@Dai所述,IN不能仅使用一个变量进行参数化。 Sure it can be done with a series of parameters but the number of them is fixed. 当然可以通过一系列参数来完成,但是它们的数量是固定的。 The idea with prepare statements is that the insertion of values are expected the same position, the same number of parameters and the same kind. 使用prepare语句的想法是,期望在相同位置,相同数量的参数和相同种类的值中插入值。

If the amount of parameter inside of the IN is fixed, something like this works: 如果IN内部的参数数量是固定的,则类似以下内容的工作:

$a=[1,2,3];
$s=$mysqli->prepare("SELECT id FROM users WHERE role_id IN (?,?,?)");
$s->bind_param('iii',$a[0],$a[1],$a[2]);
$s->execute();
$s->bind_result($id);
$c=[];
while($s->fetch()){
  $c[]=$id;
}
var_dump($c);

Maybe this is not the answer that you are looking for, but if the amount of variables is not know better insert the imploded array string inside the original SQL command. 也许这不是您要寻找的答案,但是如果不知道变量的数量,最好将插入的数组字符串插入原始SQL命令中。

$a=[1,2,3];
$b="('".implode("','",$a)."')";
$s=$mysqli->prepare("SELECT id FROM users WHERE role_id IN {$b}");
$s->execute();
$s->bind_result($id);
$c=[];
while($s->fetch()){
  $c[]=$id;
}
var_dump($c);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM