【问题标题】:PHP - Closing a MySQLi connection in a try... catch... finally blockPHP - 在 try...catch...finally 中关闭 MySQLi 连接
【发布时间】:2017-06-22 00:10:31
【问题描述】:

try... catch... finally 块中关闭 MySQLi 连接的最佳方法是什么?

这似乎确实有效,但在第一个 if 语句 (Warning: mysqli::close(): Couldn't fetch mysqli in /path-to-file/ on line 33) 上失败时会出错

代码如下:

<?php
    session_start();

    if (isset($_POST["login-submit"])) {
        require("db-config.php");

        try {
            $mysqli = @new mysqli($dbHost, $dbUser, $dbPass, $dbName);
            if ($mysqli->connect_error) {
                throw new Exception("Cannot connect to the database: ".$mysqli->connect_errno);
            }

            $username = $_POST["login-username"];
            $password = $_POST["login-password"];

            if (!($stmt = @$mysqli->prepare("SELECT * FROM users WHERE username = ?"))) {
                throw new Exception("Database error: ".$mysqli->errno);
            }

            if (!@$stmt->bind_param("ss", $username)) {
                throw new Exception("Bind error: ".$mysqli->errno);
            }

            if (!@$stmt->execute()) {
                throw new Exception("Execution error: ".$mysqli->error);
            }

        } catch (Exception $exception) {
            $error = $exception->getMessage();
            echo $error; #for debugging

        } finally {
            if ($mysqli != null) $mysqli->close();
            if ($stmt != null) $stmt->close();
        }
    }
?>

【问题讨论】:

  • 你需要先调用stmt->close()。
  • 你为什么要关闭它?
  • 这不是更好、更安全且通常是一种好的做法吗?

标签: php mysqli connection try-catch-finally


【解决方案1】:

根本不要关闭它!在脚本结束时手动关闭连接是没有意义的。执行脚本后,如果曾经打开过连接,则连接将自动关闭。您的代码还有其他问题。

try-catch 在您的代码中没有真正的用途。只需将其删除。此外,仅仅为了手动抛出异常而使 mysqli 错误静音是没有意义的。您根本没有添加任何价值,而只是在创建混乱的代码。

您的固定示例应如下所示:

<?php

session_start();

if (isset($_POST["login-submit"])) {
    require "db-config.php";

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
    $mysqli->set_charset('utf8mb4');

    $username = $_POST["login-username"];
    $password = $_POST["login-password"];

    $stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
}

通过切换自动错误报告,您可以确保如果发生错误,则会引发异常。异常就像一个错误,它会停止你的脚本。当脚本执行停止时,PHP 会清理并关闭连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    相关资源
    最近更新 更多