Nidhi Kaushal
Nidhi Kaushal

Reputation: 299

Out of memory error in php

I am on php 5.2.5 and executing a script from command line. In this script I am manipulating the data fetched from db. To fetch data from db I am using Zend Adapter. I notice an increase in memory(262144 bytes) after invoking "fetchAll($sql,$data,Zend_Db::FETCH_ASSOC)"

Hence finally leading to out of memory. To test I just executed "fetchAll" without even storing the data returned by it in any variable. But still I see an increase in memory which is not reclaimed.

I have tried using memory_get_usage() to determine the cause of memory leak, but since the code is huge it is taking a lot of time, is there any way I can get the details of all the objects in memory so that I can debug the issue better?

The sql is:-

select b.Id as Id,b.Lang 
from groups g 
left join table1 b on b.Group_Id = g.Id 
left join table2 bs on bs.Id = b.Id 
where g.Id = ? and b.Lang = ?

Upvotes: 3

Views: 2020

Answers (3)

chickenchilli
chickenchilli

Reputation: 3548

You can just fetch the result row by row without loading it into memory:

   /**
    * @var $select \Zend_Db_Select
    **/
    if ($stmt = $select->query()) {
        while ($row = $stmt->fetch()) { //... }
    }

Upvotes: 0

symcbean
symcbean

Reputation: 48357

To test I just executed "fetchAll" without even storing the data

But you've already stored 2 copies of the data. Most databse clients will maintain a buffer of data returned by the server (in the case of mysql, this has the full data set). When you call fetchAll() then the entire dataset is retrieved to the buffer (if it's not already there) and this is then mapped to a PHP array.

Do you have an explicit closeCursor call?

Upvotes: 0

deceze
deceze

Reputation: 522081

To return all results at once, they have to be stored in an array in memory. Even if you do not assign that result to any variable, fetchAll internally still has to build that array. If there are too many results to store in memory at once, you'll run out of memory; very simple.

As for why the memory is not always reclaimed: there may be a memory leak, but it's more likely that PHP's garbage collector simply does not kick in immediately to reclaim the memory. You can try forcing a gc cycle using gc_collect_cycles to confirm that.

Upvotes: 1

Related Questions