Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from mysql table WHERE field='$array'?

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

$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.

like image 436
tarnfeld Avatar asked Mar 04 '10 21:03

tarnfeld


People also ask

How do I query an array in MySQL?

Following is an elementary syntax structure to code for MySQL WHERE IN Array command in MySQL server to fetch information using array values and WHERE IN clause: SELECT ColumnName1, ColumnName2, …., ColumnNameNFROM TableNameWHERE ColumnName1 IN(ColumnName1_Value1, ColumnName1_Value2, ColumnName1_Value3);

Can we use array in where clause in SQL?

We can pass an array with the help of where IN clause. Let us first create a new table for our example.

How do I select a specific field in MySQL?

If you want to select only specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the name_id, firstname and lastname fields from the master_name table.


2 Answers

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.

like image 166
Pekka Avatar answered Oct 01 '22 17:10

Pekka


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) . ")";
like image 26
Mark Byers Avatar answered Oct 01 '22 19:10

Mark Byers