1
\$\begingroup\$

I am confused if I can do like this:

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

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

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

I tested and it does work but is it wrong?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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->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:

\$\endgroup\$
6
  • \$\begingroup\$ So you say that i can use it before while loop? \$\endgroup\$
    – Ingus
    Commented May 2, 2019 at 8:49
  • \$\begingroup\$ Also i did read that if you do not use $stmt->close(); you could have memory leak? \$\endgroup\$
    – Ingus
    Commented May 2, 2019 at 8:50
  • \$\begingroup\$ Before $count_rows = $result->num_rows; \$\endgroup\$ Commented May 2, 2019 at 8:51
  • \$\begingroup\$ @Ingus Did you read that online? In that case it is useful to add the link to your comment, otherwise we cannot verify your source. I cannot find any up-to-date source for it. Also, if memory leaks are what you fear, why then do you not use $result->free()? \$\endgroup\$ Commented May 2, 2019 at 10:58
  • \$\begingroup\$ @KIKOSoftware i did read that in one comment in one page that i cant find anymore. .. Maybe was misread info. I m new to prepared statements so i did not know free() \$\endgroup\$
    – Ingus
    Commented May 2, 2019 at 12:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.