Imploded PHP integer array for Mysql NOT IN clause

Trevor picture Trevor · Jun 15, 2011 · Viewed 12.3k times · Source

I've been trying to use a PHP integer array for a MySQL query that uses the NOT IN clause, but despite no errors it seems to always return the results I want filtered out.

Example:

$IDS = $_SESSION['Posts'];
$Select = 'SELECT * 
             FROM status 
            WHERE (W_ID = '.$ID.') 
              AND (ID NOT IN ("'.implode(',', $IDS).'")) 
         ORDER BY ID DESC 
            LIMIT '.$Begin.', '.$Number.'';

$Select = mysql_query($Select) OR DIE(mysql_error());

I'm pretty sure this is a logical syntax error.

What I've tested for:

I've made sure that $IDS is treated as an array. Also I have tested to see whether there are values stored within the array. I have also not quoted the integer array, but then I got a mysql syntax error for not having them.

Answer

Michael picture Michael · Jun 15, 2011

The problem is the two in the beginning and the end of the IN block. They cause the entire implode array to become a comma-separated string.