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

巧了我就是萌 提交于 2019-12-07 06:36:44

问题


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()?


回答1:


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



来源:https://stackoverflow.com/questions/8996499/php-prepared-statements-freeresult-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!