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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。