Mr Coder Mr Coder - 1 month ago 6
MySQL Question

How to manage empty IN sql query?

$ids = array(1,2,3);
$in = implode(',',$ids);

$query = "SELECT * FROM user where user_id IN ($in) ";


Query works no problem. But when
$ids
is empty array
$ids = array();


I got sql query error rightly so because
SELECT * FROM user where user_id IN ()
is not a valid query .

How can I avoid such situation without checking for empty array i.e making query run no matter what ?

Answer

Best way to manage this is:

$in = implode("','",$ids); // generate like 1','2
$query = "SELECT * FROM user where user_id IN ('$in') "; //  if has  1','2 surrond it with quote make it IN('1','2') and if empty than IN('')

This saves you from if/else structure and everything else