Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imploded PHP integer array for Mysql NOT IN clause

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.

like image 607
Trevor Avatar asked Jan 20 '23 11:01

Trevor


2 Answers

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.

like image 172
Michael Avatar answered Jan 29 '23 11:01

Michael


Your actual query will look like this:

ID NOT IN ("1,2,3,4")

"1,2,3,4" is one string, not several values. Get rid of the " quotes.

like image 24
deceze Avatar answered Jan 29 '23 11:01

deceze