Why do we close the result in Thoughts

Why are we closing $ result

    $mysqli = new mysqli("localhost", "root", "root", "test");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: " . $mysqli->connect_error;

    if ($result = $mysqli->query("Select * from user")) {
        while ($row = $result->fetch_object())



source to share

1 answer

Check to see if the connection has ended with the code using the connection. Obviously this won't work because this is not a live connection. Make sure that when the connection fails, the code that depends on it is not reached. (Note that I don't need to defend using logout or die. They can make a pretty bad user experience. They can be helpful, but ideally you should print a better message and leave an ugly error for the logs [retest or is this a command line script ]).

As for close () (which is actually an alias for free ()):

free () basically frees up all the stuff associated with the result. You need to understand that there are two ways to make finding strings easier (simplified, but with it):

Buffered - Everything is captured in one go. In other words, by the time you start iterating over the records, they are still in memory. They are buffered. They are not fetching from the server every time you call fetch (), but rather fetching from memory.

No buffering - there may be a small buffer, but essentially every time you call fetch () PHP has to pull a new row from the database. At the beginning of the cycle, they are not all sitting in memory.

Interesting side note: num_rows () can be called in a buffered query very efficiently since all rows have already been pulled (although you should never pull all rows just to count them), which is what COUNT is for. Unbuffered queries cannot execute num_rows () until they have pulled all rows. Meaning this will either be an error, or essentially turn it into a buffer request.

Anyway, back to your actual question:

free () frees everything associated with the result object. In the case of a buffered request, these are any lines sitting in memory. In the case of an unbuffered request, free () will free any rows that might be sitting in memory and then discard the rest of the request. Basically its PHP is telling MySQL, "Hey, you know all those lines I'm asking for? Changed my mind. You can just drop this request."

As for if you have to free the results ... Well, whenever the variable goes out of scope *, it will happen anyway. However, there is no harm in doing this explicitly, and in situations where a request might use a lot of memory and then another request after it might use a lot of memory, you can free sets to just use memory.

* Or maybe when the request completes. I don't remember from my head.



All Articles