MySQL PHP - SELECT WHERE id = array()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9476146/
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 PHP - SELECT WHERE id = array()?
提问by alex
Possible Duplicate:
MySQL query using an array
Passing an array to mysql
I have an array in PHP:
我在 PHP 中有一个数组:
$array = array(1, 4, 5, 7);
As you can see, I have an array of different values, but I want to write a MYSQL statement that will check if the id
is equalto any of the values in the array. For example, if a row has an id
of 1, it will return that row, the same for 4, 5, and 7. The length of the array can vary due to the nature of the program, so that's where the problem is. Could I just do:
正如你所看到的,我有不同的值的数组,但我想要写一个MYSQL语句,将检查,如果id
是等于任何数组中的值。例如,如果一行的id
值为 1,它将返回该行,对于 4、5 和 7 也是如此。数组的长度可能因程序的性质而异,这就是问题所在。我能不能这样做:
SELECT ...
FROM ...
WHERE id = '$array'
Or is there a better way?
If I was unclear, please ask me for more info.
或者,还有更好的方法?
如果我不清楚,请向我询问更多信息。
回答by alex
Use IN
.
使用IN
.
$sql = 'SELECT *
FROM `table`
WHERE `id` IN (' . implode(',', array_map('intval', $array)) . ')';
回答by Nathan Taylor
What you are looking for is the IN()
statement. This will test if a given field contains any of 1 or more values.
您正在寻找的是IN()
声明。这将测试给定字段是否包含 1 个或多个值中的任何一个。
SELECT * FROM `Table` WHERE `id` IN (1, 2, 3)
You can use a simple loop to convert your $array
variable into the proper format. Be sure to be mindful of SQL injection if your array values are coming from the front end.
您可以使用一个简单的循环将$array
变量转换为正确的格式。如果您的数组值来自前端,请务必注意 SQL 注入。
回答by Ben D
Simply use the ID IN ()
syntax:
只需使用ID IN ()
语法:
$sql = "SELECT FROM `table` WHERE `ID` IN (".implode(',',$array).")";
回答by Mosty Mostacho
You can write your query like this:
您可以像这样编写查询:
select * from table where id in (1, 4, 6, 7)
You can add as many values as you need.
您可以根据需要添加任意数量的值。
回答by yoozer8
You can SELECT WHERE id IN (item1, item2...)
. Just loop through your PHP array to build your array for the query.
你可以SELECT WHERE id IN (item1, item2...)
。只需循环遍历您的 PHP 数组即可为查询构建数组。
回答by David Faber
You'll want to use the IN
operator:
您将要使用IN
运算符:
$sql = 'SELECT FROM WHERE id IN (' . implode(",", $array) . ')';
$sql = 'SELECT FROM WHERE id IN (' . implode(",", $array) . ')';
There may be a limit in MySQL on how many values you can use in a list with the IN
operator.
在 MySQL 中,您可以使用IN
运算符在列表中使用多少个值可能有限制。