简体   繁体   中英

MySQL Advanced Query multiple AND and OR

I'm drawing a blank this late at night after programming all day and maybe someone else can help shed light on where my issue lies. I'm trying to make a MySQL query in PHP where it gets the correct fields based on multiple variables using AND and OR.

Here is what I'm trying to do that is not working:

$result = mysql_query("SELECT * FROM tableName 
      WHERE key = '$key' ((userFrom = '$userFrom' AND userTo = '$userTo') 
                       OR (userFrom = '$userTo' AND userTo = '$userFrom')");

Basically in English what this does is it needs to know the Key value. Once it matches the key value then I need all the rows with that key value that are ALSO - FROM or TO the same users - think of it as a conversation between two people it has to have their conversation topic (key) and the two participants (from and to).

Any suggestions?

Looks like three open parens and two closing parens to me. The missing one is immediately before the closing double quote. (Plus, of course, the missing AND mentioned by others).

Also, of course, various characters embedded in user names (if allowed) will make the command fail in data-specific ways. For that reason, and to avoid SQL Injection attacks, please switch to parameterized queries.

I think it's just a question of getting the parenthesis the correct way. Try this:

$result = mysql_query("SELECT * FROM tableName 
                       WHERE key = '$key' **AND** 
                       ((userFrom = '$userFrom' AND userTo = '$userTo') OR 
                        (userFrom = '$userTo' AND userTo = '$userFrom')");

Or perhaps:

$result = mysql_query("SELECT * FROM tableName 
                        WHERE ((key = '$key') AND 
                        ((userFrom = '$userFrom' AND userTo = '$userTo') OR 
                         (userFrom = '$userTo' AND userTo = '$userFrom'))");

I think if you fiddle with those you will get what you want.

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