Home > Backend Development > PHP Tutorial > Why Can't I Connect to My Local MySQL Server via PHP's mysqli Class?

Why Can't I Connect to My Local MySQL Server via PHP's mysqli Class?

Barbara Streisand
Release: 2024-12-04 00:34:10
Original
478 people have browsed it

Why Can't I Connect to My Local MySQL Server via PHP's mysqli Class?

Troubleshooting "Can't Connect to MySQL Server" Error when Using Localhost

When attempting to establish a connection to a MySQL database using the mysqli class in PHP, an error may arise:

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)
Copy after login

This error indicates an issue with the connection through the specified socket, 'MySQL'.

Socket Usage in localhost Connections

When connecting to localhost using "localhost" as the host, MySQL attempts to utilize a Unix domain socket for a faster and potentially more secure connection. However, if the socket is not configured or accessible, the connection fails with error 2.

Resolving the Connection Issue

To resolve this issue, several approaches can be taken:

1. Using TCP/IP Instead of Unix Socket:

Replace "localhost" with the IP address 127.0.0.1 in your connection string. This will force a TCP/IP connection.

2. Setting mysqli.default_socket:

Locate the my.cnf configuration file for MySQL and identify the path to the socket. Then, open the php.ini file and set the 'mysqli.default_socket' value to this path.

3. Configuring the Socket in the PHP Script:

Include the socket path directly in the PHP script when establishing the connection, as shown below:

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

By implementing one of these solutions, you can bypass the Unix socket connection and establish a successful connection to your MySQL database.

The above is the detailed content of Why Can't I Connect to My Local MySQL Server via PHP's mysqli Class?. 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