Concepts
PHP Manual

Buffered and Unbuffered queries

Queries are buffered by default. This means that query results are stored in memory, which allows additional operations like counting the number of rows, and moving (seeking) the current result pointer.

Unbuffered MySQL queries execute the query and then return a resource that points to the result set. This uses less memory, and allows MySQL to continue executing the query as the result set is used. It also increases load on the server.

Because buffered queries are the default, the examples below will demonstrate how to execute unbuffered queries with each API.

例1 Unbuffered query example: mysqli

<?php
$mysqli  
= new mysqli("localhost""my_user""my_password""world");
$uresult $mysqli->query("SELECT Name FROM City"MYSQLI_USE_RESULT);

if (
$uresult) {
   while (
$row $uresult->fetch_assoc()) {
       echo 
$row['Name'] . PHP_EOL;
   }
}
$uresult->close();
?>

例2 Unbuffered query example: pdo_mysql

<?php
$pdo 
= new PDO("mysql:host=localhost;dbname=world"'my_user''my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERYTRUE);

$uresult $pdo->query("SELECT Name FROM City");
if (
$uresult) {
   while (
$row $uresult->fetch(PDO::FETCH_ASSOC)) {
       echo 
$row['Name'] . PHP_EOL;
   }
}
?>

例3 Unbuffered query example: mysql

<?php
$conn 
mysql_connect("localhost""my_user""my_pass");
$db   mysql_select_db("world");

$uresult mysql_unbuffered_query("SELECT Name FROM City");
if (
$uresult) {
   while (
$row mysql_fetch_assoc($uresult)) {
       echo 
$row['Name'] . PHP_EOL;
   }
}
?>

Concepts
PHP Manual