What are the best practices for handling mysqli query results in PHP to avoid errors like "Couldn't fetch mysqli_stmt"?

When handling mysqli query results in PHP, it is important to properly check for errors and handle them gracefully to avoid issues like "Couldn't fetch mysqli_stmt". One common mistake is not checking if the query was successful before trying to fetch results. To prevent this error, always check if the query was successful using mysqli_stmt::execute() and handle any errors that may occur.

// Example of handling mysqli query results to avoid "Couldn't fetch mysqli_stmt" error
$stmt = $mysqli->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);

if ($stmt->execute()) {
    $stmt->store_result();
    $stmt->bind_result($id, $name);
    
    while ($stmt->fetch()) {
        echo "ID: $id, Name: $name <br>";
    }
} else {
    echo "Error executing query: " . $stmt->error;
}

$stmt->close();