Home > Database > Mysql Tutorial > Why Can't My PHP Code Connect to the Local MySQL Server Through the Socket?

Why Can't My PHP Code Connect to the Local MySQL Server Through the Socket?

Susan Sarandon
Release: 2024-12-11 08:08:10
Original
820 people have browsed it

Why Can't My PHP Code Connect to the Local MySQL Server Through the Socket?

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)
Copy after login

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:

  • Specify the Hostname: Use 127.0.0.1 or the IP address of the local server as the hostname instead of "localhost." This will force the client to use TCP/IP instead of the socket.
  • Set the Socket Path: Locate the path to the MySQL socket ("/var/run/mysqld/mysqld.sock" is a common location) and set PHP's mysqli.default_socket configuration option to that path.
  • Configure the Socket Directly: Specify the socket path directly in the PHP script when establishing the connection using the socket parameter. For example:
$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock');
Copy after login

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!

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