How can one improve error handling in PHP when working with MySQLi?

When working with MySQLi in PHP, it is important to improve error handling to catch and handle any potential issues that may arise during database operations. One way to enhance error handling is by using the `mysqli_report()` function to enable MySQLi to throw exceptions instead of errors. This allows for more robust error handling and easier debugging of database-related problems.

// Enable MySQLi to throw exceptions for better error handling
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

try {
    // Perform database operations
    // For example, executing a query
    $result = $mysqli->query("SELECT * FROM table");
    
    // Handle the result
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            // Process each row
        }
    } else {
        throw new Exception("Query failed");
    }
} catch (Exception $e) {
    // Handle any exceptions or errors
    echo "Error: " . $e->getMessage();
}

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