Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 循环遍历查询结果集时内存泄漏_Php_Pdo_Doctrine Orm - Fatal编程技术网

Php 循环遍历查询结果集时内存泄漏

Php 循环遍历查询结果集时内存泄漏,php,pdo,doctrine-orm,Php,Pdo,Doctrine Orm,我需要你的帮助,以超过PHP的内存限制。 这是我的代码片段,导致问题: $stmt = $query->execute(); // $stmt is instance of Doctrine\DBAL\Driver\PDOStatement $before = $stmt->fetch(); while ($after = $stmt->fetch()) { // there will be some logic for comparsion of row pairs

我需要你的帮助,以超过PHP的内存限制。 这是我的代码片段,导致问题:

$stmt = $query->execute(); // $stmt is instance of Doctrine\DBAL\Driver\PDOStatement
$before = $stmt->fetch();
while ($after = $stmt->fetch()) {
    // there will be some logic for comparsion of row pairs $before and $after,
    // but once the memory issue is fixed
    $before = $after;
    // tried unset($after); with no effect
}
错误消息是:

Fatal error: Allowed memory size of 134217728 bytes exhausted
(tried to allocate 24 bytes) in script.php on line 84
线路上的错误点:

while ($after = $stmt->fetch()) {

澄清一下,这是我真实的、运行的代码中的一部分。这不是仅仅为了问我的问题而创建的伪代码。我注释掉了循环中的所有逻辑,以确保这不是原因。

您可能需要先取消设置
$before

$stmt = $query->execute(); // $stmt is instance of Doctrine\DBAL\Driver\PDOStatement
$before = $stmt->fetch();
while ($after = $stmt->fetch()) {
    // there will be some logic for comparsion of row pairs $before and $after,
    // but once the memory issue is fixed
    unset($before);
    $before = $after;

}

“泄漏”可能发生在循环中重新分配
$before
且旧数据未被某些垃圾收集删除和/或仍在内存中徘徊时。

解决方案非常简单。PDO将整个结果缓冲到内存: 我必须设置PDO属性

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

您确定这实际上是一个“泄漏”,而不仅仅是代码通过逻辑或巨大的结果集(数字或行,或大数据块)消耗了那么多内存吗?关键是,我注释了逻辑,将其从执行中排除。在我的帖子中,有没有经过修改和简化的真实代码。好的,那么,请看我评论的第2点:您的结果集有多大,行和blob?顺便说一句:如果这是MySQL,您可以使用
PDO::MySQL\u ATTR\u USE\u BUFFERED\u QUERY
。您可以返回一行或十亿(这可能是问题所在),可能生成这么多结果的逻辑执行起来有点困难,但我们无法提供帮助,因为您既没有显示您的查询,也没有向我们提供有关实际问题的任何信息。我想知道为什么会发生这种情况,或者是如何发生的。重新分配表明$before不再引用相关对象。如果没有其他引用,GC应该释放它吗?