mysql WHERE子句包含多个值的变量 - 不起作用

时间:2014-06-25 05:27:04

标签: php mysql

我从table1的变量中获取了一个列值,并试图使用该变量从带有WHERE子句的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作为会话,并在我的show类所在的另一个文件中的WHERE子句中使用此变量。

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变量值的所有值,而不仅仅是匹配的最后一个值。

3 个答案:

答案 0 :(得分:0)

为什么不按预期使用您的关系数据库(使用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);

答案 1 :(得分:-1)

首先要做的是'$ theseOpCodeVal'逗号分隔值,然后使用'IN'运算符,如:

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

答案 2 :(得分:-1)

首先存储所有操作码

$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());