Home > Database > Mysql Tutorial > Why Can't I Connect to MySQL via Unix Socket?

Why Can't I Connect to MySQL via Unix Socket?

Linda Hamilton
Release: 2024-12-16 07:57:16
Original
823 people have browsed it

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:

  1. Use IP Address Instead (TCP/IP): Change the host to 127.0.0.1 or the actual IP address of the local server. This forces the connection to use a TCP/IP socket instead of the Unix socket.
  2. Modify my.cnf (PHP's Socket Setting): In the MySQL configuration file (my.cnf), find the location where MySQL creates the socket and set mysqli.default_socket in PHP's php.ini to that path.
mysqli.default_socket = /var/run/mysqld/mysqld.sock
Copy after login
  1. Direct Socket Configuration:
$db = new MySQLi('localhost', 'kamil', '***', '', 0, 
                              '/var/run/mysqld/mysqld.sock')
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template