php database ai_generated true

PDOException: SQLSTATE[HY000] [2002] Connection refused

ID: php/pdo-connection-failed

Also available as: JSON · Markdown
86%Fix Rate
88%Confidence
105Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 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.
  2. 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:

  1. 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.

  2. 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.

Error Chain

Leads to:
Preceded by:
Frequently confused with: