Skip to content

next_result

In this article, we will focus on the mysqli_next_result() function in PHP, which is used to advance to the next result set after executing multiple queries with mysqli_multi_query().

Introduction to the mysqli_next_result() function

The mysqli_next_result() function is a built-in PHP function that advances the result pointer to the next result set when multiple queries are executed using mysqli_multi_query(). It returns a boolean value indicating success or failure.

How to use the mysqli_next_result() function

To use mysqli_next_result(), execute your queries with mysqli_multi_query(), then iterate through the results. It is recommended to check mysqli_more_results() before calling mysqli_next_result() to avoid warnings from non-result queries (e.g., INSERT or UPDATE). Here is an example:

How to use the mysqli_next_result() function?

php
<?php
$mysqli = mysqli_connect("localhost", "username", "password", "database");

if (!$mysqli) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = "SELECT * FROM table1; SELECT * FROM table2; SELECT * FROM table3;";

if (mysqli_multi_query($mysqli, $query)) {
    do {
        /* process current result set */
        if ($result = mysqli_store_result($mysqli)) {
            // process result set
            mysqli_free_result($result);
        }
    } while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli));
} else {
    echo "Multi-query failed: " . mysqli_error($mysqli);
}

mysqli_close($mysqli);
?>

In this example, we establish a connection with error handling, then execute multiple queries using mysqli_multi_query(). The do...while loop checks mysqli_more_results() to safely advance through each result set using mysqli_next_result(), preventing warnings from non-result queries. mysqli_store_result() is used here to load the result set into memory, but it is optional; for large datasets, mysqli_use_result() or direct fetching may be more memory-efficient. Finally, we close the connection with mysqli_close().

Conclusion

In conclusion, the mysqli_next_result() function is a useful tool for advancing to the next result set when processing multiple queries with mysqli_multi_query(). By understanding how to use the function alongside mysqli_more_results(), you can efficiently execute and process multiple queries with PHP's MySQLi extension.

Practice

What does the PHP mysqli::next_result function do?

Dual-run preview — compare with live Symfony routes.