Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQLi query results: Best approach, do you close, free, both?
    text
    copied!<p>I have some questions about using <a href="http://en.wikipedia.org/wiki/MySQLi" rel="noreferrer">MySQLi</a>, queries, and related memory management. The code here is just to clarify my questions, so don't dump on it for error checking, etc. I know that needs to be done :)</p> <p>Suppose I have something like this:</p> <pre><code>@ $db = new mysqli($dbhost, $un, $ps, $dbname); $query = "SELECT field1, field2 ". "FROM table1 ". "WHERE field1={$some_value}"; $results = $db-&gt;query($query); while ($result = $results-&gt;fetch_object()) { // Do something with the results } $query = "SELECT field1, field2 ". "FROM table2 ". "WHERE field1={$some_value2}"; // question 1 $results = $db-&gt;query($query); while ($result = $results-&gt;fetch_object()) { // Do something with the second set of results } // Tidy up, question 2 if ($results) { $results-&gt;free(); } if ($db) { $db-&gt;close(); } // Question 3, a general one </code></pre> <p>So, based on the comments in the code above, here are my questions:</p> <ol> <li><p>When I assign the results of the second query to <code>$results</code>, what happens to the memory associated with the previous results? Should I be freeing that result before assigning the new one?</p></li> <li><p>Related to 1, when I do clean up at the end, is cleaning up just the last results enough?</p></li> <li><p>When I do try to clean up a result, should I be freeing it as above, should I be closing it, or both?</p></li> </ol> <p>I ask question 3 because the <a href="http://en.wikipedia.org/wiki/PHP" rel="noreferrer">PHP</a> documentation for <code>mysqli::query</code> has an example that uses close, even though close is not part of <code>mysqli_result</code> (see example 1 in <em><a href="http://ca3.php.net/manual/en/mysqli.query.php" rel="noreferrer">mysqli::query</a></em>). And in contrast, my normal PHP reference text uses <code>free</code> (<em>PHP and MySQL Web Development</em>, Fourth Edition, Welling and Thomson).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload