Mr Coder Mr Coder - 1 year ago 66
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
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download