将mysqli预准备语句的多行结果绑定到多维数组中

时间:2015-05-01 16:56:10

标签: php mysql arrays multidimensional-array mysqli

我有一个mysql查询从数据库中提取了许多行,我想将这些结果绑定到一个多维数组中。

$sample = array();
$samples = array();
//bind results into $sample array
$stmt->bind_result($sample['id'], $sample['name'], $sample['image_path'],
    $sample['main_text'], $sample['nose'], $sample['palate'], $sample['finish'],
    $sample['sample_price'], $sample['retail_price'], $sample['retail_url']);
//fetch each row of results and push the resultant array into the $samples array
while($stmt->fetch()) {
    $samples[] = $sample;
}

这是我希望上述内容实现的伪代码实例:

$samples = array(
0 => array(
    "id" => the item's id
    "name" => the item's name
    "image_path" => the item's image pgae
    "main_text" => the second item's main text
    "nose" => etc
    "finish" => etc
    "palate" => etc
    "sample_price" => etc
    "retail_url" => etc
1 => array(
    "id" => the second item's id
    "name" => the second item's name
    "image_path" => the second item's image page
    "main_text" => the second item's main text
    "nose" => etc
    "finish" => etc
    "palate" => etc
    "sample_price" => etc
    "retail_url" => etc

相反,我最终得到了一个完整相同项目的多维数组。更具体地说,如果我单步执行代码:

  1. 第一项清单
  2. 第二个项目进入数组,第一个项目成为第二个项目的副本
  3. 第三项进入数组,第一项和第二项成为第三项的副本 等
  4. 我的假设是$sample以某种方式通过引用推送到数组上,但这对我来说没有意义,因为php按值分配数组。

    任何人都知道我可能做错了什么?

    更新:我知道get_result()函数。不幸的是,这只有在使用MySQL本机驱动程序编译mysqli扩展时才有效 - 这是很难保证的。

1 个答案:

答案 0 :(得分:2)

简单如下:

$stmt->store_result();
$result = $stmt->get_result();
$samples = $result->fetchAll(MYSQLI_ASSOC);

<强>更新

$stmt->bind_result($r_id, $r_name, $r_image_path,
    $r_main_text, $r_nose, $r_palate, $r_finish,
    $r_sample_price, $r_retail_price, $r_retail_url);

while($stmt->fetch()) {
    $samples[] = array('is'=>$r_id, 
           'name'=>$r_name, 
           'image_path'=>$r_image_path,
           'main_text'=>$r_main_text, 
           'rose'=>$r_nose, 
           'palate'=>$r_palate, 
           'finish'=>$r_finish,
           'sample_price'=>$r_sample_price, 
           'retail_price'=>$r_retail_price, 
           'retail_url'=>$r_retail_url);
}