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:
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')
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!