632E
632E

Reputation: 11

Is there a correct way of using $stmt->close();

I have numerous statements on my website and I was wondering when and how you use $stmt->close(); correctly. Would it open vulnerabilities by leaving it open?

In this example, would the correct place to close the statement be line 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;
        }
    }
}

There are two statements here, would I close both? Or do I just close them both at the bottom? Also, as I am using header('Location:') does the $stmt->close(); actually get executed?

Upvotes: 1

Views: 67

Answers (1)

Dharman
Dharman

Reputation: 33257

You do not need to use $stmt->close(); at all. You almost never need to close anything manually in PHP. PHP will close it for you once it is no longer needed. If you structure your code properly, PHP will close everything for you when it is most optimal.

Using header('Location:') doesn't affect mysqli objects. When you exit the code, the whole script stops and that is when PHP will close everything if it hasn't been closed yet.

You really should use some encapsulation. Don't use mysqli methods directly. Create some function or class which will abstract from this interface and it will be easier for you to use it. If you do it properly, then you do not need to worry at all about closing the objects.

Upvotes: 1

Related Questions