简体   繁体   中英

PHP Using mysql query with multiple OR

Okay soo i didnt 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 dosnt work for me ive looked for 1 and a half hour for the answer some place now but i cant solve it. sorry if its a very easy thing but im very new to php

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.

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'
    )"
);

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 . "')"); 

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