Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage empty IN sql query?

Tags:

sql

php

mysql

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

like image 773
Mr Coder Avatar asked May 07 '12 11:05

Mr Coder


1 Answers

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

like image 132
Falcon Avatar answered Oct 16 '22 02:10

Falcon