PDOException SQLSTATE[HY000]: What It Means and How to Fix Each Error Code
Quick answer: SQLSTATE[HY000] is a generic "general error" code; what matters is the number and the text after it. The most common ones are 2002 (can't reach MySQL: wrong host or port, or the server is down), 1045 (wrong user or password, or the user isn't allowed from that host), 1049 (database doesn't exist) and 2006 (connection dropped). Read the full message in the log, then check host, port, credentials and permissions.
A typical message looks like this:
PDOException: SQLSTATE[HY000] [1045] Access denied for user 'app'@'localhost' (using password: YES)
The HY000 part tells you almost nothing. The number in brackets (1045) is the MySQL or MariaDB error code, and that is what points to the cause. This guide covers the codes you are most likely to see and how to fix each one.
First, see the full error
Configure PDO to throw exceptions and log the complete message (never show it to visitors: it can contain the database user and host):
<?php
try {
$pdo = new PDO(
'mysql:host=127.0.0.1;port=3306;dbname=app;charset=utf8mb4',
getenv('DB_USER'),
getenv('DB_PASS'),
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
} catch (PDOException $e) {
error_log('DB connection failed: ' . $e->getMessage());
http_response_code(500);
exit('Service temporarily unavailable.');
}
Since PHP 8.0, ERRMODE_EXCEPTION is the default, but setting it explicitly documents the intent. See how to find PHP errors in the logs.
The most common SQLSTATE[HY000] codes
| Code | Message | Usual cause |
|---|---|---|
| 2002 | Connection refused / No such file or directory | MySQL not running, wrong host or port, or socket problem with localhost |
| 2002 | Connection timed out | Firewall or security group blocking port 3306, wrong IP |
| 1045 | Access denied for user | Wrong password, or the user isn't allowed from that host |
| 1049 | Unknown database | Wrong database name, or it wasn't created |
| 1044 | Access denied for user to database | User has no privileges on that database |
| 2006 | MySQL server has gone away | Idle connection timed out, or a packet bigger than max_allowed_packet |
| 1040 | Too many connections | max_connections reached, often by leaked or persistent connections |
| 2054 | Authentication method unknown to the client | Old PHP client with MySQL 8's caching_sha2_password |
| 1366 | Incorrect string value | Charset mismatch (emoji or accents in a non-utf8mb4 column) |
| 2014 | Cannot execute queries while other unbuffered queries are active | A previous result set wasn't fully read or closed |
2002: can't connect to MySQL
"No such file or directory" with host=localhost: PHP tries a Unix socket and can't find it. Use host=127.0.0.1 to connect over TCP, or set the right socket path (unix_socket=/var/lib/mysql/mysql.sock).
"Connection refused": nothing is listening on that host and port. Check:
sudo systemctl status mysqld # or mariadb / mysql
sudo ss -ltnp | grep 3306 # is it listening, and on which address?
If MySQL listens only on 127.0.0.1 (bind-address), remote connections are refused.
"Connection timed out": a firewall is dropping the connection. On AWS, check the database's security group (RDS) or the instance's; on Linux, firewalld or ufw. On RHEL, CentOS and Amazon Linux with SELinux, Apache/PHP can't open connections to a remote database until you allow it:
sudo setsebool -P httpd_can_network_connect_db 1
In Docker, localhost inside the PHP container is the container itself: use the database service name (for example host=db).
1045: Access denied for user
MySQL users are identified by user and host: 'app'@'localhost' and 'app'@'%' are different accounts with separate passwords. Check which ones exist:
SELECT user, host, plugin FROM mysql.user WHERE user = 'app';
- Confirm the password, without spaces or line breaks copied from a
.envfile; - Connecting with
127.0.0.1makes MySQL see the host as127.0.0.1, which may not match a user created forlocalhost; - Create or fix the account and grant only what the app needs:
CREATE USER 'app'@'localhost' IDENTIFIED BY 'a-long-random-password';
GRANT SELECT, INSERT, UPDATE, DELETE ON app.* TO 'app'@'localhost';
1049 and 1044: unknown database, or no access to it
1049 means the database in dbname= doesn't exist on that server: check the name (it is case-sensitive on Linux) and that you are connecting to the right server. 1044 means the user exists but has no privileges on that database: grant them with GRANT ... ON database.*. This also happens when a second database is added and the app's user was only granted the first one.
2006: MySQL server has gone away
- Long scripts and workers: the connection sat idle longer than
wait_timeout, and MySQL closed it. Reconnect when you catch the error, or open the connection right before you need it; - Large inserts or blobs: the query is bigger than
max_allowed_packet. Insert in smaller batches or raise the setting on the server; - The server restarted or crashed: check the MySQL error log.
1040: Too many connections
Every PHP request that connects holds a connection until it ends. Under load, or with PDO::ATTR_PERSISTENT and many PHP-FPM workers, the server runs out. Check that workers × connections per request stays below max_connections, avoid persistent connections unless you've sized for them, and look for slow queries that keep connections open.
2054: authentication method unknown
MySQL 8 uses caching_sha2_password by default. Very old PHP versions can't use it. Update PHP (any supported version handles it), or as a temporary workaround switch that user to mysql_native_password if your MySQL version still supports it.
1366: Incorrect string value
An emoji or special character is going into a column that isn't utf8mb4. Use charset=utf8mb4 in the DSN and convert the table:
ALTER TABLE comments CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
2014: unbuffered queries are active
With unbuffered queries, you must read every row (or call $stmt->closeCursor()) before running another query on the same connection. Either fetch the results completely, close the cursor, or keep buffered queries (the default).
"could not find driver"
This one comes without SQLSTATE: the pdo_mysql extension isn't installed or enabled for the PHP that runs the site. Install it (php-mysqlnd on RHEL/Amazon Linux, php-mysql on Debian/Ubuntu), restart PHP-FPM or Apache, and confirm with php -m | grep pdo and phpinfo(). The CLI and the web server can load different extensions.
Errors in queries (not connections)
Errors in SQL itself usually come with other SQLSTATE codes, such as 42S02 (table doesn't exist), 42S22 (unknown column) or 23000 (duplicate key). Run the same query in your database client to see it fail in isolation, and always use prepared statements with parameters; see preventing SQL injection with PDO.
Don't leak database errors
An uncaught PDOException can print the user, host and query to the screen. Turn off display_errors in production, catch the exception, log the details and return a generic message (or a JSON error in an API; see error handling in a PHP API). And keep credentials out of the code: read them from environment variables or a config file outside the web root.
Checklist
- Read the number after
HY000in the log; - Database service running and listening on the expected host and port;
127.0.0.1instead oflocalhostwhen the socket isn't found;- User exists for the right host, with the right password and grants;
- Firewall, security group and SELinux allow the connection;
charset=utf8mb4in the DSN;pdo_mysqlenabled for the web server's PHP;- Errors logged, not displayed.
Conclusion
SQLSTATE[HY000] is only a wrapper: the code after it tells you whether the problem is the network (2002), the credentials (1045), the database name (1049), the connection lifetime (2006) or the charset (1366). Read the full message, fix that specific cause, and keep exceptions logged rather than displayed.
Frequently asked questions
What does SQLSTATE[HY000] mean?
It is the generic "general error" code. The number after it (for example 1045 or 2002) identifies the real problem.
Why does localhost fail but 127.0.0.1 works?
With localhost, PHP connects through a Unix socket; if the socket path is wrong, it fails. 127.0.0.1 uses TCP.
Why does my password work in the terminal but not in PHP?
The terminal may connect as a different user@host (for example through the socket as localhost), or the password in your config has extra spaces or quotes.
How do I fix "MySQL server has gone away"?
Reconnect after long idle periods, send large data in smaller batches, or raise wait_timeout and max_allowed_packet on the server.
Can my remote database connection be blocked by SELinux?
Yes, on RHEL, CentOS and Amazon Linux. Enable httpd_can_network_connect_db.