Php – thesqli_store_result() vs. thesqli_use_result()

mysqliPHP

The question

What is the difference between mysqli::store_result() and mysqli::use_result()?

The story

Vague documentation

The documentation on PHP.net seems very vague about the difference between the two. The mysqli::use_result()-page does not offer any code-samples, and links you to the mysqli::multi_query()-page to look for them. In that page the following code-sample is given (see the page for the full code):

/* store first result set */
if ($result = $mysqli->store_result()) {
    while ($row = $result->fetch_row()) {
        printf("%s\n", $row[0]);
    }
    $result->free();
}
/* print divider */
if ($mysqli->more_results()) {
    printf("-----------------\n");
}

The mysqli::store_result()-page uses exactly the same code-sample, with one exception:

/* store first result set */
if ($result = $mysqli->use_result()) {

Yeah… store_result became use_result. Note that even the comment above is still saying "store".

Even more confusing

Having seen the code samples, I thought; "all right, so it's an alias". But wait! The documentation gives the following descriptions:

They seem like two different things, and are not brought like aliases at all. Taking a closer look I found out that there was yet another exception in the code-sample of the mysqli::use_result()-page: $result->free(); became $result->close();. However my hopes for finding out the truth were soon after shattered, when I found that on that same page in the second code sample (the procedural equivalent), mysqli_free_result($result); was used, and not the expected mysqli_close_result($result);.

Best Answer

mysqli::store_result() will fetch the whole resultset from the MySQL server while mysqli::use_result() will fetch the rows one by one.

This is also mentioned in the mysqli::use_result docs you linked to:

The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

You can usually always use mysqli::store_result() unless you have a good reason for not reading all rows from the server at once.

Related Topic