Fetching table using mysqli, closing statement before displaying results I am confused if I can do like this:

$param = "%{$id}%";
$stmt = $conn-&gt;prepare("SELECT name, comp, date FROM stats WHERE date = ? AND name LIKE ? ORDER BY date DESC LIMIT 20");
$stmt-&gt;bind_param("ss", $param, $_POST['date']);
$stmt-&gt;execute();
$result = $stmt-&gt;get_result();
$count_rows = $result-&gt;num_rows;
$stmt-&gt;close(); // CAN I CLOSE IT HERE

while($row = $result-&gt;fetch_assoc()){
    echo '
    &lt;tr&gt;
        &lt;td&gt;'.$row['name'].'
        &lt;td&gt;'.$row['comp'].'
        &lt;td&gt;'.$row['date'].'
    &lt;/tr&gt;';
}


Question is can i close $stmt-&gt;close(); where i do it now or should i close it after while loop?

I tested and it does work but is it wrong?
As soon as you are finished using your $stmt object, it is practical to close it.

However, I find that I am never calling $stmt-&gt;close(); in any of my projects because php is going to trash them as soon as my script is done anyhow.

Technically, you could have called it one line earlier.

Some leisure reading:


$stmt->close() vs $stmt->free_result()
When to close Prepared Statement
PHP - close prepared stmt
When is the right time to close a prepared statement?