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

2021-12-25 00:00:00 php mysql mysqli prepared-statement

在完成准备好的 mysqli 时,我试图澄清 $stmt->close() 和 $stmt->free_result() 之间的区别强>声明.

I am trying to clarify the difference between $stmt->close() and $stmt->free_result() when finalizing a prepared mysqli statement.

到目前为止我使用:

$mysqli = new mysqli(host,user,password,database);
$stmt = $mysqli->prepare(sql statement);
[...]
$stmt->free_result();
$mysqli->close();

一切似乎都正常.

但我见过很多程序员使用 $stmt->close 而不是 $stmt->free_result().一旦我看到了他们两个:

But I've seen a lot of programmers use $stmt->close instead of $stmt->free_result(). And once I've seen both of them:

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

那么我应该选择什么,在什么情况下以及为什么?

So what should I choose, under which circumstances and why?

推荐答案

$stmt->free_result() 释放与结果集相关的内存,而 $stmt->close() 释放与准备好的语句相关的内存.随后调用 $stmt->close() 将取消任何剩余的结果.

$stmt->free_result() frees up memory related to a result set, whereas $stmt->close() frees up memory related to a prepared statement. Subsequently calling $stmt->close() will cancel any result still remaining.

本质上,调用 $stmt->close() 将提供与调用 $stmt->free_result() 相同的效果,因为它取消了结果集以及.但是调用 $stmt->free_result() 不会清除准备好的语句使用的内存,在这种情况下你必须使用 $stmt->close().

In essence, calling $stmt->close() will provide the same effect as calling $stmt->free_result() since it cancels the result set as well. But calling $stmt->free_result() will not clear out the memory used by the prepared statement in which case you must use $stmt->close().

至于使用哪个 - 可能在某些情况下,您打算使用已初始化的准备好的语句,但不再需要您当前拥有的结果集.在这种情况下,您将等待调用 $stmt->close() 直到完成准备好的语句,然后调用 $stmt->free_result()在执行另一个语句之前.

As far as which one to use goes - there may be situations where you intend on using the prepared statement you have initialized, but are no longer in need of the result set you currently have. In such a case you would wait on calling $stmt->close() until you are done with the prepared statement and instead call $stmt->free_result() before executing another statement.

相关文章