dongxing9219 2015-09-05 20:47
浏览 75
已采纳

在无缓冲查询的上下文中,foreach是等效的吗?

I am wondering -- if this code:

// example 1
$statement = $pdo->query('SELECT * FROM table'); // MySQL
while ($row = $statement->fetch())
{
  // doing something interesting
}

is equivalent of this code:

// example 2
$statement = $pdo->query('SELECT * FROM table'); // MySQL
foreach ($statement as $row)
{
  // doing something interesting
}

in context of unbuffered queries in MySQL? (I am aware the loops give the same results.)

Or in other words:

I tried something like that:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$statement = $pdo->query('SELECT * FROM table WHERE x = 1');
while(...) OR foreach(...)
{
  // some magic
}
 OR
$statement->fetch(); // just fetch(), not fetchAll()

$statement = $pdo->query('SELECT * FROM table WHERE x = 2'); // MySQL
...

And:

  1. In case of while or foreach the code runs without errors.
  2. In case of just fetch(), I, as supposed, get error: 2014.

So it seems, that I answered my own question;) But I'm still not sure. I couldn't find any docs or an SO question that would answer my problem, either.

  • 写回答

2条回答 默认 最新

  • dongliyun3301 2015-09-06 17:27
    关注

    PHP 5.5.12, Windows

    I did some more tests. I created a table with 100 000 records and I checked how much memory is taken when all values in the table are summed with different methods:

    +----------+-------------+--------+
    | method   | memory used | time   |
    +----------+-------------+--------+
    | fetchAll | 69.9157 MB  | 7.20 s |  // <-- fails if memory_limit < 69 M
    | while    | 0.2494 MB   | 3.24 s |
    | foreach  | 0.2494 MB   | 0.98 s |  // <-- here I disagree with Ollie
    +----------+-------------+--------+
    

    Taking into account the test from my question and the tests above, I conclude that:

    • using foreach and while is equivalent in terms of buffering queries: both methods read row by row and after execution of the loop all data is fetched in such way, that a next query won't throw error 2014
    • foreach does not do something like fetchAll to get the whole resultset before iterating over PDOStatement: if it did, the test would fail when memory_limit < 69M (IMHO: it's quite logic, 'cause PDOStatement implements Traversable interface). So I cannot agree with Ollie Jones' answer (at least on my computer and environment).
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境