Leandragem
Leandragem

Reputation: 98

Memory Exhausting in mysql_free_result()

I made a method on my class to fetch and store in a array all the results the desired SQL statement has in it, and it works just fine. Now, after some months in production, I came across this error:

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 3503272 bytes) in C:\xxpathxx\class.DGC_Gerais.php on line 0

As I begin to inspect, I tracked the error to the mysql_free_result(), but upon commenting that line, it still doenst work.

Here's the _fetch method:

PUBLIC static function _fetch($sql){
        $q = mysql_query($sql);

        if(mysql_num_rows($q) > 0):

            for($a=0 ; $linha = mysql_fetch_row($q) ; $a++){ // forEach row.
                foreach($linha as $chave => $valor): // forEach field.
                    $result[$a][$chave] = $valor;
                endforeach;

            }

//          mysql_free_result($q);

            return $result;

        else:
            return false;
        endif;

    }

Upvotes: 0

Views: 358

Answers (1)

deceze
deceze

Reputation: 522081

  1. That code is extremely convoluted and can be simplified to:

    public static function _fetch($sql) {
        $q = mysql_query($sql);
    
        if (mysql_num_rows($q) == 0) {
            return false;
        }
    
        $result = array();
        while ($linha = mysql_fetch_row($q)) {
            $result[] = $linha;
        }
        return $result;
    }
    

    Does exactly the same without double loops.

  2. The problem is that you're fetching all that data from the database and are storing it in $result, which means it needs to be stored in memory. And PHP limits the amount of memory available to scripts by default, so you're simply exceeding that limit. mysql_free_result has nothing as such to do with it. First try to fetch less data, or to process the data inside that while loop without needing to store everything in an array.

    If that doesn't help, carefully turn up the memory limit with ini_set('memory_limit', $limit).

Upvotes: 1

Related Questions