Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-正在尝试关闭MySQLi连接。。。抓住。。。最后封锁_Php_Mysqli_Connection_Try Catch Finally - Fatal编程技术网

PHP-正在尝试关闭MySQLi连接。。。抓住。。。最后封锁

PHP-正在尝试关闭MySQLi连接。。。抓住。。。最后封锁,php,mysqli,connection,try-catch-finally,Php,Mysqli,Connection,Try Catch Finally,在try中关闭MySQLi连接的最佳方式是什么。。。抓住。。。最后block 这似乎在总体上是可行的,但在第一个if语句中失败时会出现错误(警告:mysqli::close():无法在/path to file/第33行获取mysqli) 代码如下: <?php session_start(); if (isset($_POST["login-submit"])) { require("db-config.php"); try {

try中关闭MySQLi连接的最佳方式是什么。。。抓住。。。最后
block

这似乎在总体上是可行的,但在第一个
if
语句中失败时会出现错误(
警告:mysqli::close():无法在/path to file/第33行获取mysqli

代码如下:

<?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();
}

您需要先调用stmt->close()。为什么要关闭它?这不是更好、更安全、更普遍的好做法吗?