我有一个数组,其中包含记录id如下:
Array
(
[0] => 113
[1] => 43
[2] => 64
)
所以要实现相应的记录,我必须运行3个查询:
select * from mytable where id=113
select * from mytable where id=43
select * from mytable where id=64
我的问题:难道不可能在整个表上执行一个查询,然后通过传递ID直接访问mysqli结果?
像$record = $res['id'][113];
?
thanks in advance
您需要IN子句
SELECT * FROM mytable WHERE id IN ( 113,43,64 );
自定义函数indexme
接受数组的数组(数字或关联),默认情况下获取每个子数组的第一个元素值,并将其作为返回数组中的关联索引。可选地,可以将列名作为第二个参数传递,以指定要用于索引的列值。
$array = array(array('id' => 12, 'name' => 'Joe'), array('id' => 9, 'name' => 'Jane'));
$array_keyed = indexme($array);
// > array(12 => array('id' => 12, 'name' => 'Joe'), 9 => array('id' => 9, 'name' => 'Jane'));
print $array_keyed[12]['name'];
// > Joe
function indexme($arr, $key = '') { // <- custom function indexme
$return_arr = array();
if ( '' == $key ) {
$keys = array_keys($arr[0]);
$key = $keys[0];
}
foreach ( $arr as $value ) {
$return_arr[$value[$key]] = $value;
}
return $return_arr;
}
将mysqli响应传递给这个函数,以创建一个ID索引数组:
$results_keyed = indexme($result->fetch_assoc(), 'id');
查看本页上接受的答案MySQL准备语句与可变大小的变量列表为WHERE IN
技术的一个很好的解决方案。