PHP PDOException: Could Not Connect to Database
A PDO connection exception means PHP could not establish the requested database connection. The exact exception message usually provides the most useful clue.
Check the Connection Settings
Confirm the database host, database name, username, and password. On shared hosting, the database name and username may include an account prefix.
$dsn = "mysql:host=localhost;dbname=app_db;charset=utf8mb4";
$pdo = new PDO($dsn, $dbUser, $dbPassword, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
Use the actual values from the hosting control panel. Keep credentials outside the public web root.
Confirm the PDO Driver
The PHP runtime serving the website must have the MySQL PDO driver enabled. A CLI check is useful, but verify the website's PHP configuration too.
php -m | grep -E 'PDO|pdo_mysql'
Check Database Permissions and Availability
Confirm that the database exists, the user is assigned to it, and the required privileges are granted. Check whether the database server is running and whether the configured host is correct.
Handle Errors Safely
Log technical details privately. Show visitors a generic error message rather than database credentials, connection strings, or raw exception traces.
Summary
Verify connection settings, the PDO MySQL driver, database availability, and user privileges. Use private logs to identify the precise cause.