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.
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);
We can pass an array with the help of where IN clause. Let us first create a new table for our example.
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.
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.
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) . ")";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With