Error 500 when fetching many records

-1

I'm trying to display data in a table through a foreach in php of more than 17 thousand records in the database, but it shows HTTP ERROR 500 in the browser.

 <?php foreach($dados as $dado):?>
   <tr>
      ... // aqui vai os registros
   </tr>
 <?php endforeach;?>

The interesting thing is that when I limit the amount of records to display, for example 5,000, the error does not occur.

Would this be a memory problem with php ?

Maybe I should not use foreach ?

Edit:

Apache log:

[Fri Sep 21 10:06:00 2018] [error] [client 192.168.0.100] PHP Fatal error:  
Allowed memory size of 134217728 bytes exhausted (tried to allocate 27316224 
bytes) in Unknown on line 0, referer: 
http://192.168.0.100/index.php/relatorio/
    
asked by anonymous 21.09.2018 / 14:15

1 answer

0

The error is happening because your script is consuming more features than php is configured to allow. You could increase the limit, but I do not recommend it to be the equivalent of throwing the dust under the rug.

Ideally you would inspect your code to find out where the memory leak is. I've been through a similar problem and refactoring the code I was able to reduce the memory usage from 3GB to 300MB. One of the changes I made was to change the foreach to a for as follows:

for ($i=0, $n = count($dados); $i < $n; $i++){
    $dado = $dados[$i]; //Instancia uma variável para trabalhar nesse escopo

    ... //Sua lógica aqui, usando $dado;

    unset($dados[$i]); //Libera memória a cada interação

}

You can measure memory consumption by adding memory_get_usage() at the beginning or end of each loop interaction.

echo ((memory_get_usage(true)/1024)/1024) . 'MB';

NOTE: I read today that the use of a foreach ($foo as &$bar) loop is lighter when using heavy data arrays. But use with caution because that same syntax tends to be the slowest when using very little data.

    
21.09.2018 / 15:54