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

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

Patricia Arquette
Release: 2024-12-23 13:14:14
Original
297 people have browsed it

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

Can't Connect to MySQL Server through Socket: Troubleshooting

When connecting to a MySQL database using PHP's mysqli class, you may encounter the error "Can't connect to local MySQL server through socket 'MySQL' (2)." This indicates that the MySQL client library is attempting to connect via a Unix domain socket rather than a TCP/IP connection.

Unix Domain Socket vs. TCP/IP Connection

By default, the MySQL client library uses a Unix domain socket when connecting to localhost. This is a faster and more secure connection method, but it can only be used with localhost. To connect to MySQL using TCP/IP instead, specify 127.0.0.1 as the host name or use the --protocol=TCP option.

Solutions to the Error

There are several ways to resolve this error:

  • Use TCP/IP Connection: Change the host name to 127.0.0.1 in your PHP script to force a TCP/IP connection.
  • Configure Socket Path: Locate the path to the Unix socket in the MySQL configuration file (my.cnf) and set php.ini's mysqli.default_socket to that path.
  • Configure Socket Directly in PHP: Use the socket parameter when opening the connection to specify the socket path directly, as shown in the example below:
$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock')
Copy after login

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