Mysql where id is in array

bhttoan picture bhttoan · Nov 25, 2013 · Viewed 121.2k times · Source

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.

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:

$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(5) { 
    [0]=> int(1) 
    [1]=> int(2) 
    [2]=> int(3) 
    [3]=> int(4) 
    [4]=> int(5) 
}

Any idea where I am screwing up?

Answer

Crayon Violent picture Crayon Violent · Nov 25, 2013
$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')