How can PHP developers handle errors related to SQL queries in their code?

To handle errors related to SQL queries in PHP, developers can use try-catch blocks to catch exceptions thrown by database operations. By wrapping SQL queries in a try block and catching any exceptions in the catch block, developers can gracefully handle errors and prevent them from crashing the application.

try {
    // Connect to the database
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    
    // Execute the SQL query
    $stmt = $pdo->query("SELECT * FROM mytable");
    
    // Process the query results
    foreach ($stmt as $row) {
        // Handle each row
    }
} catch (PDOException $e) {
    // Handle any SQL query errors
    echo "Error: " . $e->getMessage();
}