How can one handle errors effectively when using MySQLi in PHP?

To handle errors effectively when using MySQLi in PHP, you can use the try-catch block to catch any exceptions that may occur during database operations. This allows you to gracefully handle errors and prevent them from crashing your application.

<?php
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check for connection errors
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Use try-catch block to handle errors
try {
    // Perform database operations here
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

// Close the connection
$mysqli->close();
?>