Next_result() is a crucial function when using PHP's MySQLi extension for database multi-query operations. It is used to process multiple result sets after a stored procedure or send multiple SQL statements at once. However, many developers ignore a detail when using next_result() : before calling next_result() , it may cause serious problems.
When executing multiple SQL statements using mysqli::multi_query() , each statement may return a result set. You need to use store_result() or use_result() to process the current result set, and then use next_result() to move to the next result set.
$mysqli = new mysqli("localhost", "user", "password", "database");
$sql = "SELECT * FROM users; SELECT * FROM products;";
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
print_r($row);
}
$result->free(); // A very important step
}
} while ($mysqli->next_result());
}
Mysqli::next_result() works as long as the current result set has been cleared or released. If you skip the store_result() or free() steps, next_result() may not be moved correctly to the next result set, resulting in subsequent query results never being processed.
Here are the most common error messages:
Commands out of sync; you can't run this command now
This error means that you have the wrong order of operations on MySQL, such as trying to execute a new query or access the next result set before processing the current result set.
Although PHP's garbage collection mechanism can usually automatically process resources, in large data volumes or long connection scenarios, if the current result set is not manually free() , it may cause slow memory growth, which will ultimately affect application performance.
Always call store_result() and free() the current result set in time.
Use a clear loop structure to ensure that each result set is processed cleanly.
Add error checks for each step to avoid logical misses.
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
// Processing results
$result->free();
} else {
if ($mysqli->errno) {
echo "Query failed: " . $mysqli->error . "<br>";
}
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
When using multi_query() and next_result() , be sure to remember: processing one result set before requesting the next is the basic etiquette for you to interact well with the database. Otherwise, you may soon see many inexplicable "Commands out of sync" errors in the bug submission system of gitbox.net .