How can SQL errors be effectively handled in PHP when using OOP MySQL?

When handling SQL errors in PHP with OOP MySQL, it is important to use try-catch blocks to catch exceptions thrown by the MySQLi class. This allows for graceful error handling and prevents the script from crashing if a SQL error occurs. Additionally, you can use the `mysqli_error()` function to retrieve the specific error message from MySQL.

<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Attempt a query
try {
    $result = $mysqli->query("SELECT * FROM table");
    if ($result === false) {
        throw new Exception($mysqli->error);
    }
    
    // Process the query result
    while ($row = $result->fetch_assoc()) {
        // Do something with the data
    }
} catch (Exception $e) {
    echo "SQL Error: " . $e->getMessage();
}

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