How can you check if a PDO connection in PHP is error-free?

To check if a PDO connection in PHP is error-free, you can use a try-catch block to catch any exceptions that may occur during the connection process. If an exception is caught, you can handle the error accordingly, such as displaying an error message or logging the error.

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    // Set PDO attributes here if needed
    echo "Connected successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}