Home >Backend Development >PHP Tutorial >Why Can't My PHP Script Connect to the MySQL Server via Socket?

Why Can't My PHP Script Connect to the MySQL Server via Socket?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-08 21:05:18559browse

Why Can't My PHP Script Connect to the MySQL Server via Socket?

Error: Unable to Connect to MySQL Server via Socket

Problem

When attempting to connect to a MySQL database using the PHP MySQLi class, the following error occurs:

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

Analysis

The error message suggests that the MySQL client library is attempting to connect to the server via a Unix domain socket named "MySQL," but the socket does not exist or is unavailable.

According to the MySQL documentation, the client library treats the host name "localhost" specially on Unix systems. By default, it tries to connect using a Unix socket file, even if a port number is specified.

Resolution

To resolve this error, consider the following options:

1. Use TCP/IP:

Use 127.0.0.1 as the host name instead of "localhost" when establishing the connection. This will force the library to use a TCP/IP connection, which is more reliable and portable.

2. Change Socket in php.ini:

Locate the MySQL configuration file (my.cnf) and find the path where MySQL creates the socket. Then, set PHP's mysqli.default_socket directive to that path in php.ini file.

3. Configure Socket in PHP Script:

Specify the socket directly in the PHP script when opening the connection:

$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock');

Additional Information

If connecting from a remote IP address, ensure that you have created a user with the necessary privileges for external connections in the MySQL database.

The above is the detailed content of Why Can't My PHP Script Connect to the MySQL Server via Socket?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn