Last Updated: February 25, 2016
·
7.875K
· pixeloution

Running out of Memory with PDO/PHP?

There's probably been a time when you've been working with a large number of rows coming from mySQL via PDO and you've hit an out of memory error. There's an easy solution to this problem. Everyone knows it. Right?

ini_set('memory_limit', '1024M');

This isn't really fixing the problem. Its fixing the symptom. The real issue in this case is PDO is loading the entire result set into memory because it allows the program to work with the dataset faster, and allows PDO to close the database connection. However, in some cases you just want to keep your memory usage low. There's a way to do that.

$PDO = new PDO("mysql:host=$host;dbname=$name", $user, $pass);
$PDO->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

This prevents PDO from trying to load the entire result set into memory at once, which can significantly reduce your memory usage, at a slight expense to performance.