W3docs

PDOException: SQLSTATE[HY000] [2002] No such file or directory

This error message typically indicates that there is a problem connecting to the database using PHP's PDO (PHP Data Objects) library.

This error message typically indicates that there is a problem connecting to the database using PHP's PDO (PHP Data Objects) library. The specific error SQLSTATE[HY000] [2002] No such file or directory specifically indicates that the PDO client cannot locate the MySQL socket file (common on Linux/macOS) or the TCP connection is being refused. This is most often caused by an incorrect socket path in the DSN, a mismatched pdo_mysql.default_socket setting in php.ini, or the MySQL/MariaDB service not running.

To resolve this issue, verify your connection settings and ensure the database server is active:

  1. Check the MySQL service status:

    sudo systemctl status mysql
    # or
    sudo systemctl status mariadb

    If it is not running, start it with sudo systemctl start mysql.

  2. Verify the socket path: On Unix-like systems, PDO defaults to a socket path defined in php.ini (pdo_mysql.default_socket). You can explicitly set it in your DSN:

    $dsn = 'mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=testdb';
    $pdo = new PDO($dsn, 'username', 'password');

    If you prefer TCP/IP, specify the host and port explicitly. Using 127.0.0.1 instead of localhost forces a TCP connection and bypasses socket file lookups:

    $dsn = 'mysql:host=127.0.0.1;port=3306;dbname=testdb';
    $pdo = new PDO($dsn, 'username', 'password');
  3. Confirm database credentials and firewall rules: Ensure the username, password, and database name are correct. If connecting remotely, verify that port 3306 is open and the MySQL server is configured to accept external connections.