【问题标题】:Binding multiple rows of results from mysqli prepared statement into multidimensional array将mysqli准备好的语句中的多行结果绑定到多维数组中
【发布时间】:2015-07-11 13:10:11
【问题描述】:

我有一个 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. 第三项进入数组,第一项和第二项成为第三项的副本 等

我的假设是 $sample 以某种方式通过引用被推送到数组中,但这对我来说没有意义,因为 php 按值分配数组。

有人知道我做错了什么吗?

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

【问题讨论】:

  • 你查看我的更新了吗?
  • @Alex 是的,我刚刚这样做了。效果很好,谢谢:)。出于兴趣,我想知道您能否告诉我为什么我的原始代码不起作用?

标签: php mysql arrays multidimensional-array mysqli


【解决方案1】:

就这么简单:

$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);
}

【讨论】:

  • 我相信只有当 mysqli 扩展被编译为使用 MySQL 本地驱动程序时才有效——这几乎是不可能保证的?
  • 行得通!太棒了,谢谢你。出于兴趣,我想知道我在原始代码中做错了什么?
  • 你不能 bind_result 与数组元素,必须命名为变量
  • 哇——不知道!非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多