【发布时间】: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