Q:

Memory leak on loop iterating over query result set

I need your help with exceeded memory limit in PHP.
This is fragment of my code, which causes the problem:
$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
}

Error message is:
Fatal error: Allowed memory size of 134217728 bytes exhausted
(tried to allocate 24 bytes) in script.php on line 84

Error points on line:
while ($after = $stmt->fetch()) {

To clarify up, this is my part of my real, running code. This is not pseudocode created just to ask my question. I commented out all logic from the loop to ensure it's not the reason.

A:

The solution was quite simple. PDO buffered whole result to memory:
I had to set PDO attribute
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

