数据库
首页 > 数据库> > php – 如何在mysql查询的where子句中传递数组值?

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

作者:互联网

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

    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变量的每个元素解析并分别呈现不同的输出.

解决方法:

首先,你应该在$element上调用array_unique().

如果这是您正在使用的可信数据且值从不包含单引号,那么您只需将其插入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();
    }
}

附:如果您想知道与question_name相同的行中的类型值,请务必选择两列,以便它们位于结果集中.

标签:php,arrays,sql,mysqli,where-clause
来源: https://codeday.me/bug/20190929/1834185.html