Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ::: Prepared Statements ::: freeresult() ::: close()

What is the importance of using:

$stmt->free_result();
$stmt->close();

After a database call using prepared statments like this:

$mysqli=new mysqli("database", "db", "pass", "user");

$stmt = $mysqli->prepare("SELECT email FROM users WHERE id=? ");
$stmt->bind_param('i',$_SESSION['id']);
$stmt->execute();
$stmt->bind_result($email);
while($stmt->fetch()){
     echo $email;
}
$stmt->free_result(); //why do i need this?
$stmt->close();       //why do i need this?

Im asking because I do not see any noticeable performance degradation without them. Are those commands usually only used for when I store the result using:

$stmt->store_result();

Like this:

$mysqli=new mysqli("database", "db", "pass", "user");

$stmt = $mysqli->prepare("SELECT email FROM users WHERE id=? ");
$stmt->bind_param('i',$_SESSION['id']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($email);
while($stmt->fetch()){
     echo $email;
}
$stmt->free_result(); //why do i need this?
$stmt->close();       //why do i need this?

Ultimately the question comes down to when is the appropriate time to use freeresult() and close()?

like image 707
Dan Kanze Avatar asked Nov 13 '22 11:11

Dan Kanze


1 Answers

The free_results statement tells the database engine it can release the result set.

When executing your statement, an iterator is created. The client (your app) iterates each result by either downloading them one by one or in chunk.

This allows you app to iterate millions of record without downloading all the results in one chunk.

EDIT

Free result will free memory on the client side. Useful if a single record is very large and memory needs to be freed.

See: http://php.net/manual/en/function.mysql-free-result.php

like image 124
Martin Samson Avatar answered Nov 16 '22 02:11

Martin Samson