PHPWarningDatabase ErrorJune 4, 2026

Database Error

SQLSTATE[HY000] [2002] Connection refused PDO connection attempt failed to 'localhost' at /var/www/html/application.php on line 17

What This Error Means

This error occurs when the PHP application attempts to connect to a MySQL database, but the database server is not running or is refusing connections due to a misconfigured firewall.

Why It Happens

The most common reasons for this error are: 1) the database server is not running or has crashed, 2) the MySQL port (default is 3306) is blocked by a firewall, 3) the database username or password is incorrect, or 4) the database host or server name is misconfigured.

How to Fix It

  1. 1To resolve this issue, follow these steps:
  2. 21. Ensure the database server is running and configured correctly.
  3. 32. Check the MySQL port is open in the firewall settings.
  4. 43. Verify the database username, password, and host are correct.
  5. 54. If using a local development environment, try connecting to a different database server or host.
  6. 65. Update the PHP code to use a different connection method, such as using the socket instead of TCP/IP.

Example Code Solution

❌ Before (problematic code)
PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
✅ After (fixed code)
PHP
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mydatabase', 'username', 'password');

Fix for SQLSTATE[HY000] [2002] Connection refused PDO connection attempt failed to 'localhost' at /var/www/html/application.php on line 17

Related PHP Errors

Related PHP Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error