何时调用 mysqli::close

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

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

When should i call mysqli::close? I never used to use if statements to check whether bind_param(), prep() and execute() were successful. Should I call $stmt->close() at the end of the method(below) . Or should I call it after every condition ensuring that I close the database connection even if the process fails at some stage e.g bind param.

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 退出时,它会优雅地关闭数据库连接.

When PHP exits it closes the database connections gracefully.

使用 close 方法的唯一原因是当您想要终止不再使用的数据库连接时,您有很多事情要做:比如处理和流式传输数据,但如果这很快,你可以忘记 close 语句.

The only reason to use the close method is when you want to terminate a database connection that you´ll not use anymore, and you have lots of thing to do: Like processing and streaming the data, but if this is quick, you can forget about the close statement.

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

Putting it in the end of a script means redundancy, no performance or memory gain.

什么是重要的:取消未使用的数据,如果你想避免内存泄漏(在我看来这是 PHP 核心的问题,在这种情况下)使用:

Whats is important: unset unused data, and if you will want to avoid memory leaks (which in my humble opnion are problem of PHP core in this case) use:

mysqli_kill();
mysqli_close(); 

这样套接字也被杀死了.

This way the socket is killed too.

相关文章