mysql查询where条件可以是数组,如何在MySQL查询的where子句中传递数组值?

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"]. "
";

}

}

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值