# PHP PDO Try-Catch Error Handling and Common SQLSTATE Codes

https://bihostnet.com/en/knowledgebase/article/php-pdo-try-catch-error-handling-sqlstate-codes

## Preventing Information Disclosure with Try-Catch

Uncaught PDOExceptions leak database usernames and plaintext passwords into stack traces. Wrap connection initialization and queries in try-catch blocks to log errors securely:

```
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    error_log($e->getMessage());
    http_response_code(500);
    die("A database error occurred.");
}
```

## Common SQLSTATE Error Codes

- **SQLSTATE[28000] [1045]:** Invalid database username or password. Verify permissions in cPanel MySQL Databases.
- **SQLSTATE[HY000] [2002]:** Connection refused. Verify database host is `localhost` or `127.0.0.1`.
- **SQLSTATE[42S02] [1146]:** Table does not exist. Check table naming conventions and case sensitivity.
- **SQLSTATE[23000] [1062]:** Duplicate entry violation on unique index columns.
