什么时候调用mysqli :: close

Alb*_*t M 4 php mysqli prepared-statement

我何时应该调用mysqli :: close?我从来没有习惯使用if语句来检查bind_param(),prep()和execute()是否成功.我应该在方法的末尾(下面)调用$ stmt-> close().或者我应该在每个条件之后调用它,确保我关闭数据库连接,即使进程在某个阶段失败,例如绑定参数.

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
}
Run Code Online (Sandbox Code Playgroud)

Gui*_*big 7

当PHP退出时,它会正常关闭数据库连接.

使用close方法的唯一原因是当你想要终止一个你不再使用的数据库连接时,你有很多事要做:像处理和流式传输数据,但如果这很快,你可以忘记关于密切的声明.

将它放在脚本的末尾意味着冗余,没有性能或内存增益.

什么是重要的:取消设置未使用的数据,如果你想避免内存泄漏(在我的简单操作中,在这种情况下是PHP内核的问题)使用:

mysqli_kill();
mysqli_close(); 
Run Code Online (Sandbox Code Playgroud)

这样套接字也会被杀死.