【问题标题】:Why results of PDO are two nested arrays and how to use them为什么PDO的结果是两个嵌套数组以及如何使用它们
【发布时间】:2015-06-16 21:53:10
【问题描述】:

Mytable:

+-----+-----------+
| id  |   word    |
|-----|-----------|
|  1  |   test1   |
|  2  |   test2   |
|  3  |   test3   |
+-----+-----------+

Mysql:

while($end = mysql_fetch_assoc($result)){
 echo $end["word"].' - ';
}

输出:

test1 - test2 - test3

PDO:

$result = $sth->fetchAll();
print_r($result);

输出:它是两个嵌套数组,如果我想选择一条记录,我应该这样做:

echo $result[0][word]; // output=test1
echo $result[1][word]; // output=test2
echo $result[2][word]; // output=test3

现在我想知道,有什么技巧可以让我回显 PDO 中列的所有记录吗?


编辑:

如何以非手动方式回显我的数据。有手动的:

echo $result[0][word]; // output=test1
echo $result[1][word]; // output=test2
echo $result[2][word]; // output=test3

那么我应该为 1000 行做什么?我当然不应该这样做:

echo $result[0][word]; // output=test1
echo $result[1][word]; // output=test2
.
.
.
echo $result[999][word]; // output=test1000

有什么优惠吗?

【问题讨论】:

  • 我看到mysql_fetch_assoc() 然后我看到fetchAll()mysql_ 和 PDO 不能同时使用。您必须从连接到查询保持相同的 MySQL。或者,这是两者之间的原因/比较问题差异吗?
  • @Fred-ii- 我在两个不同的示例中使用了mysql_fetch_assoc()fetchAll()
  • 你的问题还不清楚。如果您可以为未来的读者编辑您的问题,那将是最好的,以提及“使用两种不同的 API 有什么区别”类型的事情 ;-) 我认为你正在混合 MySQL API。有些人可能也不明白这个问题。
  • 请阅读手册php.net/manual/en/pdostatement.fetch.php 里面都有。
  • @Fred-ii- 我已经读过了,我不想要数组中的结果。如果 pdo,我如何访问记录数据?事实上,在 POD 中什么是等价的:while($end = mysql_fetch_assoc($result)){echo $end["word"];} ?

标签: php mysql arrays pdo


【解决方案1】:

mysql_fetch_assoc 的 PDO 等效项是 fetch: http://php.net/manual/en/pdostatement.fetch.php

fetchAll 做了类似的事情:

$result = array();
while($end = mysql_fetch_assoc($result)){
 $result[] = $end;
}
print_r($result);

所以您在 PDO 中的代码将如下所示:

while($end = $sth->fetch()) {
    echo $end["word"].' - ';
}

【讨论】:

  • 但是你的代码只会回显test1,因为你使用的是fetch()。我要test1 - test2 - test3
  • @stack: 不,这两个示例都将返回所有行 - while() 循环执行此操作。这两个提取(对于 mysql 库和 PDO/mysql 库)都将读取行并将内部指针移动到下一条记录。
【解决方案2】:

fetch() 返回 ONE 行数据,这将是一个字段数组。

fetchAll() 返回 ALL 行数据,因此您得到一个字段数组数组。

【讨论】:

  • 如果我使用fetch(),它只会返回一个结果。在 POD 中相当于什么:while($end = mysql_fetch_assoc($result)){echo $end["word"]}
  • 什么时候应该使用fetch()?是否等于limit 1(在sql中)?
  • 见鬼没有。您正在使用相同的结果集。您在循环中使用 fetch(),特别是如果您必须在构建结果结构时处理一些数据。例如while($row = fetch()) { do stuff with $row },与调用 fetchAll() 相比,它只会一次将整个结果集扔给你。
【解决方案3】:

键表示行(从零开始),子数组保存以列名作为键的列值。

【讨论】:

    猜你喜欢
    • 2011-10-22
    • 2011-07-04
    • 2014-05-27
    • 2017-10-26
    • 1970-01-01
    • 2011-08-03
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多