Reham Fahmy
Reham Fahmy

Reputation: 5063

Select statement with or operator

Let say if i've database row settings [id,user,pass,sos]

I've the following mysql statement

$username and $password could be anything whatever

$query = mysql_query ("SELECT * FROM `settings` WHERE user='$username' AND pass='$password'")

i want to say

SELECT * FROM `settings` WHERE user='$username' AND pass='$password' or sos=$username and sos=$password

so my question is how to use or within select statement

like i wanna say

user='$username'
pass='$password'
or
sos = both $username and $password

Thanks for helping

Upvotes: 0

Views: 136

Answers (6)

Borodin
Borodin

Reputation: 126722

Does it not work exactly like that? I would write

WHERE (user = '$username' AND pass = '$password')
OR ('$username' = '$password' AND sos = '$username');

Upvotes: 1

Gus
Gus

Reputation: 6871

I think you need parenthesis

SELECT * FROM `settings` WHERE (user='$username' AND pass='$password') or (sos=$username and sos=$password)

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71908

Use parentheses:

SELECT * 
FROM `settings` 
WHERE 
   (user='$username' AND pass='$password')
   OR
   (sos='$username' AND sos='$password')

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270609

You just need some parenthetical groups. I added single quotes in the second group, where you were initially missing them.

SELECT * 
FROM `settings`
WHERE 
  (user='$username' AND pass='$password')
  OR (sos='$username' AND sos='$password')

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

You could do

SELECT * 
FROM `settings` 
WHERE (user='$username' AND pass='$password') or (sos='$username' and sos='$password')

Upvotes: 1

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171371

You need to use some brackets to make sure you are correctly matching on related username/password pairs:

SELECT * 
FROM `settings` 
WHERE (user='$username' AND pass='$password') 
    or (sos='$username' and sos='$password')

However, you really need to use parameterized queries as the above is subject to SQL injection attack. See here for some examples on how to do this:

How can I prevent SQL injection in PHP?

Upvotes: 3

Related Questions