PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused
The error message "SQLSTATE[HY000] [2002] Connection refused" typically indicates that the client was unable to establish a connection to the database server.
The error message SQLSTATE[HY000] [2002] Connection refused typically indicates that the PHP client was unable to establish a network connection to the database server. This error strictly relates to network or daemon availability, not authentication (incorrect credentials trigger error 1045). Common causes include:
- The database server is not running.
- The database server is listening on a different host or port than expected.
- A firewall or security group is blocking access to the database port.
- The PHP client is configured to use a Unix socket path that does not match the database server's socket location (a frequent issue when using
localhoston macOS or Linux).
To troubleshoot the problem, check the following:
- Verify the database service is active: Run
systemctl status mysql(ormariadb/postgresql) to confirm the daemon is running. - Confirm host and port settings: Ensure your connection string uses the correct IP/hostname and port (e.g.,
3306for MySQL). If connecting tolocalhost, PHP may default to a Unix socket instead of TCP. - Check firewall rules: Verify that ports like
3306or5432are open usingsudo ufw statusor your cloud provider's security group settings. - Validate socket configuration: If using a socket, ensure the path matches your database's configuration. You can check the expected socket path with
php -i | grep pdo_mysql.default_socketand compare it to your database'ssocketdirective inmy.cnforpostgresql.conf.
Below is a minimal PHP PDO example showing how to explicitly specify the host and port to force a TCP connection instead of a socket:
<?php
$host = '127.0.0.1'; // Use IP to force TCP instead of socket
$port = 3306;
$dbname = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$dsn = "mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4";
try {
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
echo "Connected successfully.";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>If you still encounter issues after verifying these items, there may be a deeper network configuration problem or the database server itself may be misconfigured. In this case, contact your system administrator or database administrator for further assistance.