关闭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();
}
}
?>发布于 2020-06-21 05:14:13
根本不要关闭它!在脚本末尾手动关闭连接是没有意义的。一旦脚本被执行,连接将自动关闭,如果它曾经打开过。您的代码还存在其他问题。
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将进行清理并关闭连接。
https://stackoverflow.com/questions/42044279
复制相似问题