phpmyadmin 使用带有多个OR子句的MySQL查询

kgsdhlau  于 2022-11-09  发布在  PHP
关注(0)|答案(3)|浏览(202)

我没有找到任何东西可以帮助我解决这个问题:

$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

我想检查用户是player1、player2、player3还是player4的代码,但这对我不起作用。
我一直在寻找答案,但我不能解决它。我对PHP非常陌生。

laximzn5

laximzn51#

在SQL中,AND运算符优先于OR运算符。

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

顺便说一句,这段代码容易受到sql注入的攻击。请改用预准备语句,使代码更安全。

cunj1qz1

cunj1qz12#

尝试对OR进行分组,因为如果1返回true,则其组将返回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'
    )"
);
quhf5bfb

quhf5bfb3#

试试看:

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

相关问题