Patric Nøis
Patric Nøis

Reputation: 208

Using MySQL query with multiple OR clauses

I didn't find any thing that could help me solve this:

$hvorerjeg = $db->query("SELECT * 
    FROM `ts` 
    WHERE `aktiv` = '1' 
      AND `player1` = '$obj->id' 
      OR `player2` = '$obj->id' 
      OR `player3` = '$obj->id' 
      OR `player4` = '$obj->id'"); 
//Checks if user is player1 or player2 or player3 or player4

The code I want to check if the users is player1, player2, player3 or player4, but this doesn't work for me.

I've looked for the answer but I can't solve it. I'm very new to PHP.

Upvotes: 0

Views: 36

Answers (3)

Manuel Wong
Manuel Wong

Reputation: 44

Try this:

$hvorerjeg = $db->query("SELECT * 
    FROM `ts` 
    WHERE aktiv = '1' 
    AND (player1 = '" .  $obj->id . "'" . 
         " OR player2 = '" . $obj->id . "'" . 
         " OR player3 = '" . $obj->id . "'" . 
         " OR player4 = '" . $obj->id . "')"); 

Upvotes: 0

Pavlin
Pavlin

Reputation: 5528

In SQL the AND operator has precedence over the OR operator.

$hvorerjeg = $db->query("SELECT * FROM `ts` WHERE `aktiv` = '1'
  AND (
  `player1` = '$obj->id' OR
  `player2` = '$obj->id' OR
  `player3` = '$obj->id' OR
  `player4` = '$obj->id')
");

As a side note, this code is vulnerable to sql injection. Use prepared statements instead to make your code safer.

Upvotes: 2

Joey
Joey

Reputation: 1370

Try grouping the ORs since if 1 returns true their group will return true.

$hvorerjeg = $db->query(
    "SELECT * FROM `ts` WHERE 
    `aktiv` = '1' AND 
    (
        `player1` = '$obj->id' OR 
        `player2` = '$obj->id' OR 
        `player3` = '$obj->id' OR 
        `player4` = '$obj->id'
    )"
);

Upvotes: 0

Related Questions