mysqli_query single query gerenating PHP fatal error: Allowed memory size exhausted

ぃ、小莉子 提交于 2021-01-29 10:25:58

问题


I have a Mysql table (named "base") with 3 million records, which is composed of only 3 int(10) fields.

When I try to run this simple query $result = mysqli_query($db, 'SELECT * FROM base'), php shows the error:

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 10485768 bytes) in C:\xampp\htdocs\combina.php on line 17

I think mysqli_query should not load all the table records into memory, right?

So why the memory overflow?

I'm using XAMPP installation on Windows 10, PHP 7.2.

Here is the code:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "comb";

$db = mysqli_connect($servername, $username, $password, $dbname);
if (!$db) {
    die("Falha na conexão: " . mysqli_connect_error());
}
$result = mysqli_query($db, 'SELECT * FROM base');

回答1:


I researched and realized that the mysqli_query command actually loads ALL records into RAM. That is, for large tables, it will actually generate a memory limitation.

The solution I found was to use the combination of mysqli_real_query (which will activate the query without loading all the records in RAM, mysqli_use_result (which will return the resulting object not buffered ) and finally mysqli_fetch_row which will read the result line by line.

In this way the solution to the presented problem would be more or less:

$db = mysqli_connect($servername, $username, $password, $dbname);
mysqli_real_query($db, 'SELECT * FROM base');
$result = mysqli_use_result($db);
while ($row = mysqli_fetch_row($result)) {
    ...


来源:https://stackoverflow.com/questions/51550061/mysqli-query-single-query-gerenating-php-fatal-error-allowed-memory-size-exhaus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!