W3docs

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:

  1. The database server is not running.
  2. The database server is listening on a different host or port than expected.
  3. A firewall or security group is blocking access to the database port.
  4. 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 localhost on macOS or Linux).

To troubleshoot the problem, check the following:

  1. Verify the database service is active: Run systemctl status mysql (or mariadb/postgresql) to confirm the daemon is running.
  2. Confirm host and port settings: Ensure your connection string uses the correct IP/hostname and port (e.g., 3306 for MySQL). If connecting to localhost, PHP may default to a Unix socket instead of TCP.
  3. Check firewall rules: Verify that ports like 3306 or 5432 are open using sudo ufw status or your cloud provider's security group settings.
  4. 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_socket and compare it to your database's socket directive in my.cnf or postgresql.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.