Obviously, a large amount of data requires a large amount of memory when the method works. For minimal memory usage on the client side, the cursors are used relative to the base, you use it with the mysql_fetch_array function, which retrieves the next result from the cursor.
When using the mysql_query function, it buffers the result, you work with the data cursor that is processed and stored in the PHP script memory, naturally with a large amount of data, the usual amount of memory allocated for the script is not enough. This is called a buffered query.
The mysql_unbuffered_query function comes to the rescue, it does not save the result of execution into memory, but moves the cursor in the database, making the script's memory not clogged. This is called an unbuffered request.
That is, in the case of mysql_query, you work with a cursor from PHP memory, and in the second case with a database cursor. Change mysql_query to mysql_unbuffered_query and everything will be fine.
I want to note that the mysql extension is outdated and its use is insecure, at least due to the lack of parameter binding functions, and lack of support in PHP 5.5 and higher, use the mysqli or PDO library, the latter provides more convenient object-oriented data access.
Unbuffered queries have advantages and disadvantages:
Benefits:
- The result can be started to read earlier, the waiting time is reduced;
- The result does not take place in the RAM.
Disadvantages:
- It is impossible to know how many rows are received;
- It is impossible to move to a specific result, that is, you can only read data from the beginning and in order;
- No other queries can be performed until this result is closed.
An unbuffered PDO request looks like this:
<?php $pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass'); $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); $uresult = $pdo->query("SELECT Name FROM City"); if ($uresult) { while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) { echo $row['Name'] . PHP_EOL; } } ?>
On the official PHP site there is information on a buffered and unbuffered query in English.
PS If you only need an ID, select only id in the query, but not all fields from the table