Skip to content
Advertisement

Warning: mysqli_stmt::close(): Couldn’t fetch mysqli_stmt in X on line Y

I’m pretty new to php coding and managed to resolve a lot of problems myself, but there is 1 I can’t get my head around.

$prep_stmt = "SELECT id FROM members WHERE Email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);

// check existing Email
if ($stmt) {
    $stmt->bind_param('s', $Email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows == 1) {
        // A user with this Email address already exists
        $error_msg .= '<p class="error">A user with this Email address already exists.</p>';
        $stmt->close();
    }
            $stmt->close();
} else {
    $error_msg .= '<p class="error">Database error Line 39</p>';
            $stmt->close();
}

My guess is that the code can’t get to the 2nd $stmt->close(); in the above code (the one after the if inside the if).

How can I resolve this problem? Is that $stmt->close(); really needed?

Advertisement

Answer

Why you don’t just remove the first one (in the second if statement)? Also remove the close() in your else statement because you checked if $stmt is a legal object. Basically what you say is: $stmt isn’t a legal object, close it. But close what?

This will work in both situations:

$prep_stmt = "SELECT id FROM members WHERE Email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);

// check existing Email
if ($stmt) {
    $stmt->bind_param('s', $Email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows == 1) {
        // A user with this Email address already exists
        $error_msg .= '<p class="error">A user with this Email address already exists.</p>';
        //Remove this one: $stmt->close();
    }
    $stmt->close();
} else {
    $error_msg .= '<p class="error">Database error Line 39</p>';
    //This one can be removed because $stmt isn't a legal object: $stmt->close();
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement