我应该什么时候调用 mysqli::close?我从来没有使用 if 语句来检查 bind_param()、prep() 和 execute() 是否成功。我应该在方法(下面)的末尾调用 $stmt->close() 吗?或者我应该在每个条件之后调用它确保我关闭数据库连接,即使进程在某个阶段失败,例如绑定(bind)参数。
public function function_name($id,$new_id ){
$query = "UPDATE TABLE SET name = ? WHERE field = ? ";
if($stmt=$this->prepare($query)){
if($stmt->bind_param("is", $id, $new_id)){
if($stmt->execute()){
}else{//Could not execute the prepared statement
$message = "Could not execute the prepared statement";
}
}else{//Could not bind the parameters
$message = "Could not bind the parameters";
}
}else{
$message = "Could not prepare the statement";
}
return $message
}
最佳答案
当 PHP 退出时,它会优雅地关闭数据库连接。
使用 close 方法的唯一原因是当你想终止一个你不再使用的数据库连接时,你有很多事情要做:比如处理和流式传输数据,但如果这很快,你可以忘记 close 语句。
将它放在脚本的末尾意味着冗余,没有性能或内存增益。
重要的是:取消设置未使用的数据,如果你想避免内存泄漏(在我看来这是 PHP 核心问题,在这种情况下)使用:
mysqli_kill();
mysqli_close();
这样套接字也被杀死了。
关于php - 何时调用 mysqli::close,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9083341/