首页 > 解决方案 > 是否有使用 $stmt->close(); 的正确方法?

问题描述

我的网站上有很多声明,我想知道您何时以及如何$stmt->close();正确使用。它会通过保持开放来打开漏洞吗?

在这个例子中,关闭语句的正确位置是第 23 行吗?

// First, check if the email and code exists
if (isset($_GET['email'], $_GET['code'])) {
    if ($stmt = $con->prepare('SELECT * FROM accounts WHERE email = ? AND activation_code = ?')) {
        $stmt->bind_param('ss', $_GET['email'], $_GET['code']);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // Account exists with the requested email and code
            if ($stmt = $con->prepare('UPDATE accounts SET activation_code = ? WHERE email = ? AND activation_code = ?')) {
                // Set the new activation code to 'activated', this is how we can check if the user has activated their account
                $newcode = 'activated';
                $stmt->bind_param('sss', $newcode, $_GET['email'], $_GET['code']);
                $stmt->execute();

                header('Location: messages.php?message=activated');
                exit;
            }
        } else {
            header('Location: messages.php?message=activated-error');
            exit;
        }
    }
}

这里有两个语句,我要关闭它们吗?或者我只是在底部关闭它们?另外,正如我使用header('Location:')的那样,$stmt->close();实际执行了吗?

标签: phpmysqli

解决方案


你根本不需要使用$stmt->close();。您几乎不需要在 PHP 中手动关闭任何内容。一旦不再需要,PHP 会为您关闭它。如果您正确地构建代码,PHP 会在最佳状态时为您关闭所有内容。

使用header('Location:')不会影响 mysqli 对象。当您exit编写代码时,整个脚本将停止,如果尚未关闭,PHP 将关闭所有内容。

你真的应该使用一些封装。不要直接使用 mysqli 方法。创建一些将从这个接口抽象出来的函数或类,这样你就更容易使用它了。如果你做得正确,那么你根本不需要担心关闭对象。


推荐阅读