title: MySQLi query results: When do I close, free, or both?
body: <p>I have some questions about using MySQLi queries, and related memory management.</p>
  <p>Suppose I have something like this:</p>
  <pre><code>$db = new mysqli($dbhost, $un, $ps, $dbname);
  
  $query = &quot;SELECT field1, field2  FROM table1 &quot;;
  $results = $db-&gt;query($query);
  
  while ($result = $results-&gt;fetch_object()) {
      // Do something with the results
  }
  
  $query = &quot;SELECT field1, field2 FROM table2 &quot;;
  // 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 <a href="http://ca3.php.net/manual/en/mysqli.query.php" rel="nofollow noreferrer">the PHP documentation for <code>mysqli::query</code></a> has an example that uses close, even though close is not part of <code>mysqli_result</code> (see example 1 in the link above). 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>