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();
}
}
?>
根本不关闭它!在脚本结束时手动关闭连接是没有意义的。脚本执行后,如果连接曾经打开,则连接将自动关闭。您的代码还有其他问题。
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 将清理并关闭连接。