Home >Database >Mysql Tutorial >Why Can't I Connect to MySQL via Unix Socket?
Can't Connect to MySQL via Unix Socket: Can't Connect to MySQL via Socket 'MySQL' (2)
When connecting to MySQL using PHP's mysqli class and specifying "localhost" as the host, you encounter the error message "Can't connect to local MySQL server through socket 'MySQL' (2)." This indicates an issue with the Unix socket used for local connections.
Understanding Localhost Connections
By default, the MySQL client library uses a Unix domain socket to connect to the local MySQL server when the host is specified as "localhost." However, if the socket is inaccessible or does not exist, you will encounter this error.
Troubleshooting Options
To resolve this issue, you have several options:
mysqli.default_socket = /var/run/mysqld/mysqld.sock
$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock')
By specifying the socket directly, you are overriding the default Unix socket configuration.
In your case, since you are only able to connect via 127.0.0.1, using Option 1 is recommended. If you need to allow external website connections, you should create a new user with appropriate privileges and use TCP/IP (Option 1) for the remote connection.
The above is the detailed content of Why Can't I Connect to MySQL via Unix Socket?. For more information, please follow other related articles on the PHP Chinese website!