mysql的WHERE子句是一个变量,它包含多个值-不工作


mysql WHERE clause a variable which holds multiple values - is not working

我从table1中获取了一个列值,并试图使用该变量从table2中获取另一个列值。

我正在尝试下面的代码,其中$theseOpCode从user_profile表中持有OpCode列值。我想从$table WHERE OpCode='$theseOpCode'获取值。我也尝试了WHERE IN ($theseOpCode),但没有运气。

谁来告诉我正确的路。

index . php

$query=mysql_query("SELECT * FROM user_profile WHERE email='$thisEmail'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
  $theseOpCode = $row['OpCode'];  
  $_SESSION['Op'] = $theseOpCode;
}

我试图获得$theseOpCode作为一个会话,并在WHERE子句中使用这个变量在另一个文件中,我的show类是。

showClass.php

    class showClass{
public function showUser($table){
    $theseOpCodeVal = $_SESSION['Op'];
        $query=mysql_query("SELECT * FROM $table WHERE OpCode='$theseOpCodeVal'") or die(mysql_error()); 
        $data=NULL;
        if(mysql_num_rows($query)>0){
            while($rows=mysql_fetch_assoc($query)){
            $data[]=$rows;
            }
            return $data;
        }else{
            echo '<span class="text-info success">No Account Found.</span>';
        exit();
        }

    }
}

我的代码正在工作,但只显示WHERE子句的最后一个值。但是我在$theseOpCodeVal变量中有6个值。我想获取所有匹配$theseOpCodeVal变量值的值,而不仅仅是最后匹配的值

为什么不按预期使用关系数据库(使用PDO,只是因为)…

class showClass {
    private $pdo;
    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }
    public function showUser($table, $email) {
        $stmt = $this->pdo->prepare("
            SELECT a.* FROM `$table` a
            INNER JOIN user_profile b ON a.OpCode = b.OpCode
            WHERE b.email = ?");
        $stmt->execute([$email]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
$pdo = new PDO('mysql:host=localhost;dbname=whatever;charset=utf8', 'username', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$showClass = new showClass($pdo);
$thisEmail = 'wherever you got the value from in the first place';
$table = 'some_table';
$data = $showClass->showUser($table, $thisEmail);

首先存储所有的opCodes

$query=mysql_query("SELECT * FROM user_profile WHERE email='$thisEmail'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
  $theseOpCode = $row['OpCode'];  
  $_SESSION['Op'][] = $theseOpCode;
}

下一步,查询IN运算符

$query=mysql_query("SELECT * FROM $table WHERE OpCode IN ('".implode("','", $theseOpCodeVal)."')") or die(mysql_error());

首先,您必须使'$theseOpCodeVal'逗号分隔值,然后使用'IN'操作符,如:

'WHERE OpCode IN ($theseOpCodeVal)';而不是WHERE IN.