簡體   English   中英

正確關閉PHP中的數據庫連接

[英]Properly closing database connections in PHP

我在PHP數據庫連接中面臨一些疑問。 由於不能在我的方法(Java風格)上放置一個較大的try / catch / finally塊,因此當大小/邏輯趨於增加時,正確關閉所有連接和已准備好的語句的最佳方法是什么? 考慮下一種方法,一切都做對了嗎?

public function createRegister($register) {
        $this->openConnection();

        $query = "INSERT INTO register (username, password, email, confirmationToken) VALUES (?, ?, ?, ?)";
        $result = $this->mysqli->query($query);

        if ($statement = $this->mysqli->prepare($query)) {  
            $statement->bind_param("ssss", $register->username, $register->passwordHash, $register->email, $register->confirmationToken);

            if (!$statement->execute()) {
                $this->closeConnection();
                throw new DAOException("Failed to execute statement: " . $statement->error);
            }

            $statement->close();

        } else {
            $this->closeConnection();
            throw new DAOException("Failed to prepare statement: " . $this->mysqli->error);
        }

        $this->closeConnection();
    }

您仍然可以在PHP中使用try / catch:

public function createRegister($register) {

    $this->openConnection();

    $query = "INSERT INTO register (username, password, email, confirmationToken) VALUES (?, ?, ?, ?)";

    try {

        // This line is not needed
        // $result = $this->mysqli->query($query);

        if ($statement = $this->mysqli->prepare($query)) {

            $statement->bind_param("ssss", $register->username, $register->passwordHash, $register->email, $register->confirmationToken);

            if (!$statement->execute()) {                   
                throw new DAOException("Failed to execute statement: " . $statement->error);
            }

            $statement->close();

        } else {
            throw new DAOException("Failed to prepare statement: " . $this->mysqli->error);
        }
    } catch (Exception $e) {

        if ((isset($statement)) && (is_callable(array($statement, 'close')))) {
            $statment->close();
        }

        $this->closeConnection();

        throw $e;
    }

    $this->closeConnection();
}

這對於為一個特定任務建立連接非常有效,但是如果您想為需要訪問同一模式的多個任務共享同一連接怎么辦? 您可能需要考慮使用單例/工廠模式創建和訪問數據庫連接的更高級的解決方案。 我發布了這樣一個示例,作為另一個問題的解決方案。 它稍微先進一點,但是一旦您掌握了它,它的性能就會更高。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM