PDOException: SQLSTATE[HY000] [2002] Connection refused
ID: php/pdo-connection-failed
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 83 | active | — | — | — |
Root Cause
PDO connection failures occur when PHP cannot establish a connection to the database server. Common causes include incorrect host/port configuration, the database server not running, firewall rules blocking the connection, or using 'localhost' when the socket path is wrong.
genericWorkarounds
-
89% success Use 127.0.0.1 instead of localhost to force TCP connection and verify the database is running
Replace 'localhost' with '127.0.0.1' in the DSN to force TCP instead of Unix socket. Verify the database is running with 'systemctl status mysql' or 'pg_isready'. Check the port with 'ss -tlnp | grep 3306'. If using Docker, ensure the container port is mapped correctly.
-
85% success Check database server status, firewall rules, and socket configuration
Verify the database server is running and listening on the expected port. Check firewall rules with 'iptables -L' or 'ufw status'. For socket connections, verify the socket path with 'mysql_config --socket' and match it in the PDO DSN. Ensure the PHP user has permission to access the socket file.
Dead Ends
Common approaches that don't work:
-
Switching from PDO to mysqli to fix the connection
88% fail
Both PDO and mysqli use the same underlying connection mechanism. If PDO cannot connect, mysqli will fail for the same reason. Switching drivers does not fix network or configuration issues and adds unnecessary code changes.
-
Hardcoding database credentials directly in PHP files
75% fail
Hardcoding credentials does not solve connection issues and creates security vulnerabilities. If the connection is refused, the problem is with the host/port/socket, not with how credentials are stored.