Magento – Fetch Row by Row Like PDO::fetch()

ce-1.9.0.1databaseMySQL

I am running

$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = "SELECT id FROM customers_old";
$old_customers = $connection->fetchAll($sql);

But it's a HUGH table and this does not fit into memory:

PHP Fatal error: Allowed memory size of 268435456 bytes exhausted

Normally I would make a loop an fetch row by row: $connection->fetch($sql)

But fetch does not exist here and fetchRow() always returns the same row.

Solution?

Best Answer

You'll want to use the core/resource_iterator. This passes each object in a collection through a callback method. This article from Atwix (I'm not connected to them in any way) explains it really well: http://www.atwix.com/magento/working-with-large-collections/.