What is the difference in error handling between mysqli and PDO database connections in PHP?

When it comes to error handling, PDO provides a more consistent and easier way to handle errors compared to mysqli in PHP. PDO allows you to set the error mode to exceptions, which will automatically throw PDOException objects when errors occur, making it easier to catch and handle them in your code. On the other hand, mysqli requires you to manually check for errors after each database operation, which can be more cumbersome and error-prone.

// PDO error handling
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// mysqli error handling
$mysqli = new mysqli("localhost", "username", "password", "mydatabase");
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}