MySQLi 准备语句与 IN 运算符

2021-12-25 00:00:00 sql php mysqli prepared-statement

我必须使用 IN 运算符从数据库中选择一些行.我想使用准备好的语句来做到这一点.这是我的代码:

I have to select some rows from the database using IN operator. I want to do it using prepared statement. This is my code:

<?php
$lastnames = array('braun', 'piorkowski', 'mason', 'nash');
$in_statement = '"' . implode('", "', $lastnames) . '"'; //"braun", "piorkowski", "mason", "nash"

$data_res = $_DB->prepare('SELECT `id`, `name`, `age` FROM `users` WHERE `lastname` IN (?)');
$data_res->bind_param('s', $in_statement);
$data_res->execute();
$result = $data_res->get_result();
while ($data = $result->fetch_array(MYSQLI_ASSOC)) {
    ...
}
?>

虽然数据库中所有数据都存在,但是什么都不返回.

还有一点:如果我直接通过$in_statement来查询执行,会返回数据.所以问题出现在准备阶段.

我在谷歌中寻找问题,但没有成功.我的代码有什么问题?
感谢您的帮助!

But returns nothing although all data exists in the database.

And one more: if i pass $in_statement directly to query and execute it, the data will be returned. So the problem appears on preparing.

I was looking for the question in Google but it wasn't' successful. What's wrong with my code?
Thanks for the help!

推荐答案

我最近为我的问题找到了解决方案.也许这不是最好的方法,但它很好用!证明我错了:)

I've recently found the solution for my question. Maybe it's not the best way to do it, but it works nice! Prove me wrong:)

<?php
$lastnames = array('braun', 'piorkowski', 'mason', 'nash');
$arParams = array();

foreach($lastnames as $key => $value) //recreate an array with parameters explicitly passing every parameter by reference
    $arParams[] = &$lastnames[$key];

$count_params = count($arParams);

$int = str_repeat('i',$count_params); //add type for each variable (i,d,s,b); you can also determine type of the variable automatically (is_int, is_float, is_string) in loop, but i don't need it
array_unshift($arParams,$int); 

$q = array_fill(0,$count_params,'?'); //form string of question marks for statement
$params = implode(',',$q);

$data_res = $_DB->prepare('SELECT `id`, `name`, `age` FROM `users` WHERE `lastname` IN ('.$params.')');
call_user_func_array(array($data_res, 'bind_param'), $arParams);
$data_res->execute();
$result = $data_res->get_result();
while ($data = $result->fetch_array(MYSQLI_ASSOC)) {
    ...
}

$result->free();
$data_res->close();
?>

相关文章