其中id在数组中的mysql [重复]

[英]Mysql where id is in array [duplicate]


This question already has an answer here:

这个问题在这里已有答案:

I have a string of ids like 1,2,3,4,5 and I want to be able to list all rows in mysql where the ID is contained in that list.

我有一串id,如1,2,3,4,5,我希望能够列出mysql中包含该列表ID的所有行。

I assumed the easiest way would be to turn the string into an array and then match in ($array) but it doesn't work for me - no errors etc but it returns no rows:

我假设最简单的方法是将字符串转换为数组,然后匹配($ array)但它对我不起作用 - 没有错误等但它不返回任何行:

$string="1,2,3,4,5";
$array=array_map('intval', explode(',', $string));
$query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')");

If I do a var_dump of $array I get:

如果我执行$ array的var_dump,我得到:

array(5) { 
    [0]=> int(1) 
    [1]=> int(2) 
    [2]=> int(3) 
    [3]=> int(4) 
    [4]=> int(5) 
}

Any idea where I am screwing up?

知道我搞砸了吗?

3 个解决方案

#1


21  

$string="1,2,3,4,5";
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')");

#2


6  

Your query translates to:

您的查询转换为:

SELECT name FROM users WHERE id IN ('Array');

Or something to that affect.

或者那些影响的东西。

Try using prepared queries instead, something like:

尝试使用准备好的查询,例如:

$numbers = explode(',', $string);
$prepare = array_map(function(){ return '?'; }, $numbers);
$statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')");
if($statement) {
   $ints = array_map(function(){ return 'i'; }, $numbers);
   call_user_func_array("mysqli_stmt_bind_param", array_merge(
      array($statement, implode('', $ints)), $numbers
   ));
   $results = mysqli_stmt_execute($statement);
   // do something with results 
   // ...
}

#3


2  

Change

更改

$array=array_map('intval', explode(',', $string));

To:

至:

$array= implode(',', array_map('intval', explode(',', $string)));

array_map returns an array, not a string. You need to convert the array to a comma separated string in order to use in the WHERE clause.

array_map返回一个数组,而不是一个字符串。您需要将数组转换为逗号分隔的字符串,以便在WHERE子句中使用。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/11/25/378a082e19dd0d1fe76c1b68ea00e1b.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号