When attempting to establish a connection to a MySQL database using the mysqli class in PHP, an error may arise:
mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)
This error indicates an issue with the connection through the specified socket, 'MySQL'.
When connecting to localhost using "localhost" as the host, MySQL attempts to utilize a Unix domain socket for a faster and potentially more secure connection. However, if the socket is not configured or accessible, the connection fails with error 2.
To resolve this issue, several approaches can be taken:
1. Using TCP/IP Instead of Unix Socket:
Replace "localhost" with the IP address 127.0.0.1 in your connection string. This will force a TCP/IP connection.
2. Setting mysqli.default_socket:
Locate the my.cnf configuration file for MySQL and identify the path to the socket. Then, open the php.ini file and set the 'mysqli.default_socket' value to this path.
3. Configuring the Socket in the PHP Script:
Include the socket path directly in the PHP script when establishing the connection, as shown below:
$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock');
By implementing one of these solutions, you can bypass the Unix socket connection and establish a successful connection to your MySQL database.
The above is the detailed content of Why Can't I Connect to My Local MySQL Server via PHP's mysqli Class?. For more information, please follow other related articles on the PHP Chinese website!