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条)

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题