简体   繁体   中英

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 please 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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM