MySQLi prepared statements with IN operator(MySQLi 准备语句与 IN 运算符)
问题描述
我必须使用 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();
?>
这篇关于MySQLi 准备语句与 IN 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQLi 准备语句与 IN 运算符


基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01