Mysql where id is in an array

I have an identifier string like 1,2,3,4,5 and I want to be able to list all the rows in mysql where the identifier is in this list.

I assumed that the easiest way would be to turn the string into an array and then combine it into ($ array), but it does not work for me - no errors, etc., but it does not return strings:

$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 var_dump of the $ array, I get:

 array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) } 

Any idea where I'm screwing up?

+6
source share
3 answers
 $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."')"); 
+18
source

Your request is translated into:

 SELECT name FROM users WHERE id IN ('Array'); 

Or something that affects.

Try using prepared queries, for example:

 $numbers = explode(',', $string); $prepare = array_map(function(){ return '?'; }, $numbers); $statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')"); if($statement) { $ints = array_map(function(){ return 'i'; }, $numbers); call_user_func_array("mysqli_stmt_bind_param", array_merge( array($statement, implode('', $ints)), $numbers )); $results = mysqli_stmt_execute($statement); // do something with results // ... } 
+6
source

Edit

 $array=array_map('intval', explode(',', $string)); 

To:

 $array= implode(',', array_map('intval', explode(',', $string))); 

array_map returns an array, not a string. You need to convert the array to a comma separated string for use in the WHERE clause.

+1
source

Source: https://habr.com/ru/post/958797/


All Articles