Home > Backend Development > PHP Tutorial > Why is my PHP mysqli connection failing with 'Can't connect to local MySQL server through socket 'MySQL' (2)'?

Why is my PHP mysqli connection failing with 'Can't connect to local MySQL server through socket 'MySQL' (2)'?

Linda Hamilton
Release: 2024-12-02 13:17:16
Original
777 people have browsed it

Why is my PHP mysqli connection failing with

mysqli::mysqli() Error: Connecting via Socket 'MySQL' Fails

When attempting to establish a connection to a MySQL database using PHP's mysqli class, the error "mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)" indicates difficulties in establishing a connection via a Unix domain socket.

Reason for Socket Error

By default, when "localhost" is provided as the host, MySQL attempts to connect using a Unix domain socket file, "MySQL," instead of TCP/IP. However, if this socket is missing or inaccessible, a connection cannot be established.

Solutions

To resolve this issue, consider the following solutions:

  • Use TCP/IP: Explicitly provide the IP address "127.0.0.1" as the host instead of "localhost" to force a TCP/IP connection.
  • Configure PHP's MySQL Socket Path: Open the MySQL configuration file (my.cnf) and locate the path where MySQL creates the socket. Then, in your PHP script, use the mysqli.default_socket configuration to set this path for PHP.
  • Specify Socket in Script: Directly configure the socket in your PHP script using the following syntax:

    $db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock')
    Copy after login

    Host Configuration for Website

If you intend to make the database accessible from your website, you may need to configure a different host. The host configuration depends on the setup of your web hosting environment and the location of your MySQL server. It's recommended to consult your hosting provider for specific instructions on configuring a remote host.

The above is the detailed content of Why is my PHP mysqli connection failing with 'Can't connect to local MySQL server through socket 'MySQL' (2)'?. 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