How to pass array values in where clause of mysql query?

只愿长相守 提交于 2019-11-27 08:50:48

问题


I have a variable $element whose value is:

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

I want to use this variable in my query :

$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>";
    }
}

Actually I want to parse from each element of $element variable and present different output respectively.


回答1:


First, you should call array_unique() on $element.


If this is trusted data that you are using and the values never contain single quotes, then you can just insert it into an IN clause:

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

If this is not trusted data then a prepared statement with placeholders is advisable. This is slightly convoluted for an IN clause.

$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. If you want to know the type value from the same row as the question_name be sure to SELECT both columns so that they are in your resultset.



来源:https://stackoverflow.com/questions/48452010/how-to-pass-array-values-in-where-clause-of-mysql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!