SQLWarningDatabase ErrorMay 24, 2026

Database Error

SQLSTATE[HY000][2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

What This Error Means

This error occurs when the SQL client is unable to connect to the MySQL server. It typically happens when the MySQL service is not running or is not accessible.

Why It Happens

The error message indicates that the SQL client is trying to connect to the MySQL server through a socket file, but the file does not exist or is not accessible. This can be due to various reasons such as the MySQL service not being started, the socket file being deleted, or the file system permissions being incorrect.

How to Fix It

  1. 1To fix this error, you need to ensure that the MySQL service is running and the socket file is accessible. Here are the steps:
  2. 21. Check the status of the MySQL service: Use the command `sudo service mysql status` (on Ubuntu-based systems) or `sudo service mysqld status` (on Red Hat-based systems) to check the status of the MySQL service.
  3. 32. Start the MySQL service: If the service is not running, use the command `sudo service mysql start` (on Ubuntu-based systems) or `sudo service mysqld start` (on Red Hat-based systems) to start the service.
  4. 43. Verify the socket file: Check if the socket file exists and is accessible: `ls /var/run/mysqld/mysqld.sock`. If the file does not exist, you may need to recreate it.
  5. 54. Update the MySQL connection settings: Ensure that the MySQL connection settings in your PHP script or application are correct, including the hostname, username, password, and database name.

Example Code Solution

❌ Before (problematic code)
SQL
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
✅ After (fixed code)
SQL
$mysqli = new mysqli('localhost', 'username', 'password', 'database', 3306);
$mysqli->connect_errno ? die($mysqli->connect_error) : null;

Fix for SQLSTATE[HY000][2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Related SQL Errors

Related SQL Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error