如何在mysql查询的where子句中传递数组值?

时间:2018-01-25 21:13:47

标签: php sql arrays mysqli where-clause

我有一个变量$element,其值为:

    Array ( [4] => easy [5] => easy [7] => easy [8] => will [9] => easy [10] 
    => will ) 

我想在我的查询中使用此变量:

$sql = "SELECT * FROM questions where type='$element'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["question_name"]. "<br>";
    }
}

实际上我想从$ element变量的每个元素解析并分别呈现不同的输出。

1 个答案:

答案 0 :(得分:1)

首先,您应在array_unique()上致电$element

如果这是您正在使用的可信数据且值从不包含单引号,那么您只需将其插入IN子句:

$sql = "SELECT question_name FROM questions WHERE `type` IN ('" . implode("','", $element) . "')";

如果这不是可信数据,则建议使用带占位符的预准备语句。对于IN子句,这有点令人费解。

$params = $element;

$count = count($params);
$csph = implode(',', array_fill(0, $count, '?'));  // comma-separated placeholders

if(!$stmt = $conn->prepare("SELECT question_name FROM questions WHERE `type` IN ($csph);")){
    echo "Syntax Error @ prepare: " , $conn->error;  // don't show to public
}else{
    array_unshift($params, str_repeat('s', $count));  // prepend the type values string
    $ref = [];  // add references
    foreach ($params as $i => $v) {
        $ref[$i] = &$params[$i];  // pass by reference as required/advised by the manual
    }
    call_user_func_array([$stmt, 'bind_param'], $ref);    

    if (!$stmt->execute()) {
        echo "Error @ bind_param/execute: " , $stmt->error;  // don't show to public
    } elseif (!$stmt->bind_result($question_name)) {
        echo "Error @ bind_result: " , $stmt->error;  // don't show to public
    } else {
        while ($stmt->fetch()) {
            // do something with $question_name
        }
        $stmt->close();
    }
}

P.S。如果您想知道与type在同一行中的question_name值,请务必选择两列,以便它们位于结果集中。