$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 ?
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
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