Can't Connect to MySQL Server Through Socket: A Common PHP Error
When trying to establish a connection to a MySQL database using PHP's mysqli class, you may encounter the following error:
mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)
This error suggests that the MySQL client library is attempting to use a Unix domain socket for the connection, rather than a TCP/IP connection. However, the socket named "MySQL" does not exist or is inaccessible.
Understanding the Error
When you use "localhost" as the hostname for the MySQL connection, the client library automatically tries to connect via a Unix socket. This is a faster and more secure connection method on Unix-based systems. However, if the socket is not properly configured or does not exist, the connection will fail.
Ways to Resolve the Issue
To resolve this issue, you can:
$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock');
By implementing one of these solutions, you can ensure that the MySQL connection is established correctly, eliminating the "Can't connect to local MySQL server through socket" error.
The above is the detailed content of Why Can't My PHP Code Connect to the Local MySQL Server Through the Socket?. For more information, please follow other related articles on the PHP Chinese website!