How can errors be properly handled and displayed in a MySQLi login query in PHP?

When handling errors in a MySQLi login query in PHP, it is important to check for errors after executing the query and display appropriate error messages to the user if any occur. This can be done by using the `mysqli_error()` function to retrieve the error message from the database connection. By displaying clear error messages, users can understand what went wrong during the login process.

// Perform MySQLi login query
$query = "SELECT * FROM users WHERE username = ? AND password = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

// Check for errors
if($stmt->error) {
    echo "Error: " . $stmt->error;
} else {
    // Process login result
    $result = $stmt->get_result();
    if($result->num_rows > 0) {
        // Login successful
    } else {
        echo "Invalid username or password";
    }
}

// Close statement and connection
$stmt->close();
$conn->close();