从mysql表中选择字段='$array'?

时间:2022-09-21 00:41:20

If I have an array of say, some ID's of users. How could i do something like this:

如果我有一个比方的数组,一些用户的ID。我怎么能做这样的事:

$array = array(1,40,20,55,29,48);
$sql = "SELECT * FROM `myTable` WHERE `myField`='$array'";

Is there a simple way to do this, I thought about looping through array items and then building up one big "WHERE -- OR -- OR -- OR" statement but i thought that might be a bit slow for large arrays.

是否有一种简单的方法,我想过通过数组项进行循环,然后构建一个“WHERE”或“OR”语句,但是我认为对于大型数组来说,这可能有点慢。

2 个解决方案

#1


24  

Use IN:

使用:

$sql = "SELECT * FROM `myTable` WHERE `myField` IN (1,40,20,55,29,48)";

you can use implode(",", $array) to get the list together from the array.

您可以使用内爆(“,”,$array)从数组中获取列表。

#2


11  

You want to use IN:

你想在:

WHERE `myfield` IN (1,40,20,55,29,48)

Use implode to construct the string:

使用内爆构造字符串:

$sql = "SELECT * FROM `myTable` WHERE `myField` IN (" . implode(',', $array) . ")";

#1


24  

Use IN:

使用:

$sql = "SELECT * FROM `myTable` WHERE `myField` IN (1,40,20,55,29,48)";

you can use implode(",", $array) to get the list together from the array.

您可以使用内爆(“,”,$array)从数组中获取列表。

#2


11  

You want to use IN:

你想在:

WHERE `myfield` IN (1,40,20,55,29,48)

Use implode to construct the string:

使用内爆构造字符串:

$sql = "SELECT * FROM `myTable` WHERE `myField` IN (" . implode(',', $array) . ")";