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

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

DDD
DDDOriginal
2024-12-31 12:44:10187browse

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

Error Connecting to MySQL Server via Unix Socket

When trying to establish a connection to a MySQL database through the PHP MySQLi class, an error message may appear: "Can't connect to local MySQL server through socket 'MySQL' (2)."

Understanding the Error

This error indicates that the MySQL client library is attempting to use a Unix domain socket for the connection, but the socket is not configured correctly or does not exist. By default, localhost connections use a Unix socket, which can be faster and more secure than TCP/IP. However, specifying 'localhost' may not work if the socket is not configured properly.

Solving the Problem

To resolve this issue, consider the following solutions:

  • Specify TCP/IP Connection: Instead of using 'localhost,' use the IP address '127.0.0.1' to force a TCP/IP connection.
  • Check Socket Configuration in php.ini: In the MySQL configuration file (my.cnf), locate the socket path and set the PHP configuration option 'mysqli.default_socket' to that path.
  • Configure Socket Explicitly in Script: Set the socket path explicitly in the PHP script when opening the connection, as shown in the following example:
$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock');

The above is the detailed content of Why Can't I Connect to My MySQL Server via Unix 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