在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();
}
}
?>
答案 0 :(得分:0)
根本不要关闭它!在脚本末尾没有必要手动关闭连接。一旦执行脚本,连接将自动关闭(如果曾经打开过的话)。您的代码还存在其他问题。
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将清理并关闭连接。