PDO Connection Failed

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection refused

Quick Answer

PHP cannot connect to the database server. Verify the host, port, username, password, and that the database server is running and accepting connections.

Why This Happens

PDO throws this exception when it cannot establish a connection to the database. Common causes include the database server not running, incorrect host or port, wrong credentials, firewall rules blocking the connection, or the database server not accepting remote connections.

The Problem

$pdo = new PDO('mysql:host=localhost;dbname=myapp', 'root', 'wrong_password');

The Fix

try {
    $pdo = new PDO(
        'mysql:host=127.0.0.1;port=3306;dbname=myapp',
        'root',
        'correct_password',
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    error_log('Database connection failed: ' . $e->getMessage());
    throw $e;
}

Step-by-Step Fix

  1. 1

    Verify the database server is running

    Check that your MySQL/PostgreSQL server is running with systemctl status mysql or by trying to connect via the command-line client.

  2. 2

    Check connection parameters

    Verify the host, port, database name, username, and password are correct. Try using 127.0.0.1 instead of localhost to avoid socket issues.

  3. 3

    Check network and permissions

    Ensure no firewall blocks the port, the database user has proper privileges, and the server is configured to accept connections from your host.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free