php id在数组中的Mysql
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20203063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mysql where id is in array
提问by bhttoan
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.
我有一个像 1,2,3,4,5 这样的 id 字符串,我希望能够列出 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?
知道我在哪里搞砸了吗?
回答by Crayon Violent
$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."')");
NB: the syntax is:
注意:语法是:
SELECT * FROM table WHERE column IN('value1','value2','value3')
SELECT * FROM table WHERE column IN('value1','value2','value3')
回答by qwertynl
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
// ...
}
回答by Darius
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 子句中使用。

