I have a database with some records and columns: "type", "id" and others. I would like to select all records with any "type" that's mentioned in array $typearray but without records which id's are in $idarray. I tried to do something like:
$result = mysql_query("SELECT * FROM db
WHERE type IN('".implode("','",$typearray)."')
AND id NOT IN('".implode("','",$idarray)."')
ORDER BY date DESC LIMIT 10");
But it doesn't seem to work - the:
type IN('".implode("','",$typearray)."')
condition works fine but the second does not. At first I thought the issue was with column types - both arrays contains strings, "type" column is a VARCHAR(10) and id is INT, but changing it to string didn't help. What am I doing wrong?
EDIT:
If I print a query I get this:
SELECT * FROM db
WHERE type IN('apple','tomato','potato')
AND id NOT IN('20','1','10','15','8')
ORDER BY date DESC LIMIT 10
The first condition works fine: it selects only apples, tomatoes and potatoes. The second condition does nothing and even if I type manually:
id NOT IN('20','1','10','15','8')
or
id NOT IN('20,1,10,15,8')
or
id NOT IN(20,1,10,15,8)
it still fails.
EDIT2:
Actually forget it. I'm an idiot. I've mixed up my variables a bit...
You should try this query, or at least do a echo $result, "\\n";
, into mysql workbench to see what it give.
And I'd say the default behavior to have when a query does not work: first in Mysql Workbench (or any SQL runner like Toad, Squirrel ...)
$result = mysql_query("SELECT * FROM db
WHERE type IN('".implode("','",$typearray)."')
AND id NOT IN('".implode("','",$idarray)."')
ORDER BY date DESC LIMIT 10");
If $typearray
is empty, you are looking for type IN ('')
, which might never matches. If $idarray
is empty, you are looking for id not in ('')
which might always matches.
And if $typearray
or $idarray
contains invalid character, you will get an error.
[edit] by the way, if $typearray
or $idarray
may contains invalid character, you might use array_map and mysqli_escape_string :
$result = mysql_query("SELECT * FROM db
WHERE type IN('".implode("','", array_map('mysql_escape_string', $typearray))."')
AND id NOT IN('".implode("','", array_map('mysql_escape_string', $idarray))."')
ORDER BY date DESC LIMIT 10");
you don't need to escape integer variables:
...
AND id NOT IN(" . implode(",", $idarray).")
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.