1

I have an SQL statement:

$sql = "SELECT * FROM user_events WHERE userID =" . $uid . " OR groupID = (IN ($gId) WHERE userID IS NULL) ORDER BY timestamp DESC";

This looks like this when printed:

SELECT * FROM user_events WHERE userID = 34 OR groupID =(IN (44,45) WHERE uID IS NULL) ORDER BY timestamp DESC

What I'm trying to do is select from the database any row where either the userId matches a specific variable or where the groupID matches a CSV variable where the userID is NULL.

Can anyone explain what I'm doing wrong here? I'm quite stuck!

3
  • Use IN as an operator when dealing with comma-separated lists. Use = as an operator when comparing exact values. Use LIKE as an operator when comparing case-insensitive values and wildcards. They are all comparison operators and should be used as such (just like in mathematics). Commented Aug 29, 2012 at 14:44
  • 2
    Also, use prepared statements, don't concatenate strings to build a query. Commented Aug 29, 2012 at 14:45
  • If you use placeholders, a lot of the SQL query encoding issues will be handled for you. Seeing things like $uid inside a query should set your hair on fire. Commented Aug 29, 2012 at 15:06

3 Answers 3

9

IN is an operator, not a... that. You also want AND, not WHERE.

$sql = "SELECT * FROM user_events
        WHERE userID = $uid
           OR groupID IN ($gId) AND userID IS NULL
        ORDER BY timestamp DESC";
Sign up to request clarification or add additional context in comments.

Comments

1
$sql = "SELECT * FROM user_events 
       WHERE userID =" . $uid . " 
       OR (groupID IN ($gId) AND userID IS NULL) ORDER BY timestamp DESC";

Comments

0

I think that you want something like:

SELECT * FROM user_events 
WHERE (userID = 34 OR groupID IN (44,45)) and uID IS NULL
ORDER BY timestamp DESC

In PHP, this might look like:

$sql = "SELECT * FROM user_events WHERE (userID =". $uid . " OR groupID IN ($gId)) AND userID IS NULL ORDER BY timestamp DESC"; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.