Home >Backend Development >PHP Tutorial >How to Properly Handle `mysqli_next_result()` Errors in PHP\'s `mysqli_multi_query()`?

How to Properly Handle `mysqli_next_result()` Errors in PHP\'s `mysqli_multi_query()`?

DDD
DDDOriginal
2024-12-07 15:50:13869browse

How to Properly Handle `mysqli_next_result()` Errors in PHP's `mysqli_multi_query()`?

Strict Standards: mysqli_next_result() Error with mysqli_multi_query

In the provided PHP code, an attempt to use mysqli_multi_query() to execute multiple queries in a single database call triggers a strict standards error:

mysqli_next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method

To resolve this error, the following solution is offered:

do {} while (mysqli_more_results($db) && mysqli_next_result($db));

This modification ensures that mysqli_more_results() is checked before using mysqli_next_result(). Additionally, since no result sets are returned in the provided code, checking mysqli_affected_rows() instead of conditional exit might be a better approach.

A more comprehensive solution that handles queries with or without result sets using mysqli_multi_query() is provided:

if (mysqli_multi_query($mysqli, implode(';', $queries))) {
    do {
        if ($result = mysqli_store_result($mysqli)) {
            // Process result set
        }
    } while (next($queries) && mysqli_more_results($mysqli) && mysqli_next_result($mysqli));
}

if ($mysqli_error = mysqli_error($mysqli)) {
    // Handle error
}

Alternatively, a "reinvented" version of the snippet using a while loop is presented:

while ((isset($multi_query) && (next($queries) && mysqli_more_results($mysqli) && mysqli_next_result($mysqli))) || (!isset($multi_query) && $multi_query = mysqli_multi_query($mysqli, implode(';', $queries)))) {
    // Process query
}

if ($mysqli_error = mysqli_error($mysqli)) {
    // Handle error
}

These snippets provide a robust mechanism for handling multiple queries and result sets, making them suitable for a wider range of scenarios.

The above is the detailed content of How to Properly Handle `mysqli_next_result()` Errors in PHP\'s `mysqli_multi_query()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn