How do I use the empty variable in MySQL more than once?
I am trying to check for 2 empty variables in a MySQL statement but I can seem to get the syntax quite right for it. Here is what I have now and it keeps giving me an error. Can anyone pl开发者_StackOverflowease tell me how I can do this properly?
SELECT threads, userid, username, usergroupid
FROM " . TABLE_PREFIX . "user
WHERE
" . iif(!empty($exuserids), "AND userid NOT IN ($exuserids)") . "
" . iif(!empty($exgroups), "AND usergroupid NOT IN ($exgroups)") . "
ORDER BY threads DESC
LIMIT 1
Use:
SELECT threads, userid, username, usergroupid
FROM " . TABLE_PREFIX . "user
WHERE 1 = 1
" . iif(!empty($exuserids), "AND userid NOT IN ($exuserids)") . "
" . iif(!empty($exgroups), "AND usergroupid NOT IN ($exgroups)") . "
ORDER BY threads DESC
LIMIT 1
There needs to be a WHERE clause before you specify "AND ..." - the 1 = 1
will be optimized out. It's a trick used for dynamic SQL to make WHERE clause concatenation easier.
Well no wonder it gives you an error. Are you using PHPkit or something else that gives you iif
Because, despite you do not say so, the above is written in PHP and iif
is not part of the language.
Now, even if you have it why not compile the statement prettily -- gather the conditions in an array, implode with AND and add a WHERE condition if it's not empty.
Finally, having variables in queries is a recipe for SQL injection attacks.
精彩评论