October 29, 2026 - 15:59
PDO MySQL SQLSTATE[HY000] [2002]: Socket or Connection? Image
PHP

PDO MySQL SQLSTATE[HY000] [2002]: Socket or Connection?

0 Comments

When PDO reports SQLSTATE[HY000] [2002], changing the database password is not the first test to run. The PHP process may be unable to reach MySQL over TCP, may be looking for the wrong Unix socket, or may be connecting to the wrong host. Authentication failures usually appear later in the connection sequence and often use a different error code.

Determine whether the DSN uses TCP or a socket

The PDO MySQL DSN can specify a host and port or a Unix socket. On some PHP and operating-system setups, localhost uses a local socket; 127.0.0.1 targets TCP. The exact behavior depends on the driver and environment, so changing the hostname is a diagnostic test, not a guaranteed fix.

GENEL
// Example DSN for a TCP connection
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=app;charset=utf8mb4';

// Example DSN when a local socket is required
$dsn = 'mysql:unix_socket=/run/mysqld/mysqld.sock;dbname=app;charset=utf8mb4';

The socket path varies by distribution and configuration; the example is not universal. Check which socket or port MySQL is actually listening on, then test from the same host and runtime as PHP. A successful command-line connection as an administrator does not prove that the PHP-FPM user can reach the same endpoint.

If PHP runs in a container and MySQL runs in another, 127.0.0.1 usually refers to the PHP container itself, not the database container. Check the service name, port and container network. For a remote database, a listening port is only one part of the path: bind address, network rules and account host permissions are separate checks.

Separate reachability from authentication

  • Is the database service running and listening on the expected port or socket?
  • Are PHP and MySQL on the same host, or must DNS, routing and firewall rules work between them?
  • Does the deployed application use the host, port or socket value you just checked?
  • If the server is reached but access is denied, inspect the database account, password and allowed source host separately.

Do not display the full exception on a public page; it can reveal database names, paths or connection details. Log the error code and a request identifier, not secrets. PHP's PDO_MYSQL DSN reference documents host and socket options, and the PDO connection reference explains connection setup. For an application-level login example, see creating a user login system with PHP.

Related Articles

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment