views:

52

answers:

5

i have following code:

SELECT *
FROM table
WHERE thread = $thread
AND (user != $user1 OR user != $user2)

i want the code to pick all rows that contains $thread BUT the user isn't $user1 or $user2.

is my code correct? or should it be like:

SELECT *
FROM table
WHERE thread = $thread
(AND user != $user1 OR user != $user2)

thanks in advance

+1  A: 

Use this:

SELECT *
FROM table
WHERE thread = $thread
(AND user != $user1 AND user != $user2)

Because you don't want if the user is either of user1 or user2, for this reason using 'AND' will be proper option here.

Also if the $thread is not an integer field, you need enclose it in quotes eg:

WHERE thread = '$thread'
Sarfraz
+2  A: 

SELECT *
FROM table
WHERE thread = $thread
AND user != $user1
AND user != $user2

Plynx
what if thread is a string?
Sarfraz
Just following the OP's lead. Avoiding SQL injection is important, obviously.
Plynx
A: 

I think you should also be using <> instead of !=

So:

SELECT *
FROM table
WHERE thread = $thread
AND user <> $user1
AND user <> $user2
Ganesh Shankar
<> and != both are same and understood by mysql
Sarfraz
`!=` is ANSI-92, and supported by MySQL at least 4.1+
OMG Ponies
+3  A: 

Use:

SELECT t.*
  FROM TABLE t
 WHERE t.thread = mysql_real_escape_string($thread)
   AND t.user NOT IN (mysql_real_escape_string($user1), mysql_real_escape_string($user2))

Please use mysql_real_escape_string, or risk SQL injection attacks.

OMG Ponies
Mind that you don't need single quotes, because of using `mysql_real_escape_string`
OMG Ponies
i have already escaped them=)
weng
`mysql_escape_string` is deprecated, but an alternative for PHP prior to 5.3: http://php.net/manual/en/function.mysql-escape-string.php
OMG Ponies
@noname: Sorry, just making sure.
OMG Ponies
+1  A: 

You could also use

SELECT *
FROM table
WHERE thread = '$thread'
AND user NOT IN ($user1, $user2)

Don't know which executes faster, but this is my preferred way because I like it's readability better.

PhiwassailerKing