【问题标题】:why does only first mysqli_fetch() result gets stored in array为什么只有第一个 mysqli_fetch() 结果存储在数组中
【发布时间】:2020-06-05 23:13:00
【问题描述】:

我是 mysqli 准备好的语句的新手。我正在尝试将结果存储在关联数组中,以便我可以进一步使用它。结果在附加到数组之前会正确打印,但是在附加时只添加第一个条目。这里的方法有什么错误?

// order_details_table
$order_details = array();
$invoice = 1234;
$stmt = $con->prepare("SELECT `description`,`amount` FROM order_details_table WHERE invoice_no = ?");
$stmt->bind_param("s", $invoice);
$stmt->execute();
$stmt->bind_result($description,$amount);
while($stmt->fetch())
{
    print_r($description." ".$amount); //This prints all the entries for the given query
    $row['desc'] = $description;
    $row['amount'] = $amount;
    $order_details += [$row]; //This appends just the first entry
}
print_r($order_details);

【问题讨论】:

  • 把你的时间改成这个while($row = $stmt->fetch()){
  • $order_details[] = $row 会变魔术。
  • @mitkosoft 他没有覆盖。他只是在滥用数组加法运算符
  • 在你的评论中使用 $order_details[array_shift($row)] = $row; 在 while 循环 @mitkosoft 中不好
  • @Dlk 你把 PDO 和 mysqli 搞混了

标签: php arrays mysqli append prepared-statement


【解决方案1】:

您正在使用数组联合运算符。来自 PHP 文档:

+ 运算符返回附加到左侧数组的右侧数组;对于两个数组中都存在的键,将使用左侧数组中的元素,而忽略右侧数组中的匹配元素。

您的临时数组与您要收集到的数组具有相同的键。两者都有键为 0 的元素,因此不会添加新行。

要修复它,您应该使用数组推送运算符,即[]

while($stmt->fetch())
{
    print_r($description." ".$amount); //This prints all the entries for the given query
    $row['desc'] = $description;
    $row['amount'] = $amount;
    $order_details[] = $row; // Append the new row into the array
}

但是,我不推荐这种手动方法。 mysqli 具有一次获取所有行的方法。你应该改用fetch_all()

// order_details_table
$invoice = 1234;
$stmt = $con->prepare("SELECT `description`,`amount` FROM order_details_table WHERE invoice_no = ?");
$stmt->bind_param("s", $invoice);
$stmt->execute();
$result = $stmt->get_result(); // Get the result instead of binding
$order_details = $result->fetch_all(MYSQLI_ASSOC);

如果您真的想逐个循环结果并手动构建数组,请在 mysqli_result 对象上使用foreach 循环。

// order_details_table
$invoice = 1234;
$stmt = $con->prepare("SELECT `description`,`amount` FROM order_details_table WHERE invoice_no = ?");
$stmt->bind_param("s", $invoice);
$stmt->execute();
$result = $stmt->get_result(); // Get the result instead of binding
$order_details = []; // Instanciate empty array
foreach($result as $row)
{
    $newrow['desc'] = $row['description'];
    $newrow['amnt'] = $row['amount'];
    $order_details[] = $newrow; //This appends just the first entry
}
print_r($order_details);

【讨论】:

  • 您应该添加一个带有多维数组的简单 pdo 示例来回答我 :) 笑话!为什么是 foreach 而不是 while ?
  • @Dlk 让我反过来问:为什么while 而不是foreach? foreach 方法不是更简单吗?
  • 很简单!我想知道在这种情况下使用 while 和 foreach 之间是否有什么不同,而不是一般:)
  • @Dlk 有。我今天打算再写一篇文章。如果我这样做,我会在这里链接。如果没有,您可以搜索我的旧答案,我已经在某个地方解释过了。
  • @Dlk 也许这会有所帮助:stackoverflow.com/a/60343398/1839439
【解决方案2】:

使用 foreach($stmt->fetch() as $row)

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 2021-07-10
    • 2016-08-18
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2017-09-09
    相关资源
    最近更新 更多