I do several different types of checking in different situations to make sure that the sql statement is valid.
In the most basic type of checking, I make sure that the variable is not empty or false
$in = implode(',',$ids);
if(!$ids) $in="0";
$query = "SELECT * FROM user WHERE user_id IN ($ids)";
Typically, I use a whole series of db_*
functions which validate the input I pass into queries so that I can handle more advanced uses check where the $ids
array comes from
Here is some test code that works well for me in dozens of situations.
function db_number_list($lst)
{
if(!$lst)
return "0"; // if there are no passed in values , return a 0
if (!is_array($lst))
$lst = explode (",",$lst); //if a lst was passed in, create an array
foreach ($lst as $k=>$val)
{
if(!is_numeric(trim($val)))
unset($lst[$k]);//remove non-numeric values;
}
if(!count($lst))
return "0"; //if nothing is in the array after removing non-numeric values, return 0
return implode (",",$lst);
}
$ids=array();
$query = "SELECT * FROM user WHERE user_id IN (".db_number_list($ids).")";
echo "ids:'".print_r($ids,true)."'<br>$query<hr>";
$ids="1,2,45,6,";
$query = "SELECT * FROM user WHERE user_id IN (".db_number_list($ids).")";
echo "ids:'".print_r($ids,true)."'<br>$query<hr>";
$ids=array(3,6,1,"drop table x", 4);
$query = "SELECT * FROM user WHERE user_id IN (".db_number_list($ids).")";
echo "ids:'".print_r($ids,true)."'<br>$query<hr>";
Output:
ids:'Array ( ) '
SELECT * FROM user WHERE user_id IN (0)
ids:'1,2,45,6,'
SELECT * FROM user WHERE user_id IN (1,2,45,6)
ids:'Array ( [0] => 3 [1] => 6 [2] => 1 [3] => drop table x [4] => 4 ) '
SELECT * FROM user WHERE user_id IN (3,6,1,4)