The following editor will bring you an article that perfectly solves the problem of MySQL being unable to connect to the database through localhost. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.
Problem:The PHP program of a server cannot connect to the database through the localhost address, but if it is set to 127.0.0.1, it can The connection is normal, and the connection to other database servers is also normal. The permissions of MySQL are set correctly, and the database can be connected normally through the mysql command line client.
Analysis: This is a typical situation where the socket is not set correctly.
ConnectionMySQL databaseThere are two ways: TCP/IP (the commonly understood port type) and Unix socket (generally called socket or sock) . In most cases, localhost can be used to represent the local machine 127.0.0.1, but when connecting to MySQL, the two cannot be mixed, and localhost and 127.0.0.1 are also set separately in the permission settings in MySQL. When set to 127.0.0.1, the system connects to the database through TCP/IP; when set to localhost, the system connects to the database through socket.
Solution: First check where the local MySQL socket file is. The check command is:
mysqld --verbose --help | grep socket
The output results show that the socket file is The location of the interface file, for example: this server displays
socket /var/run/mysqld/mysqld.sock
and then modify the configuration file php.ini of php to correspond to it.
Find this item:
mysql.default_socket =
Generally speaking, this item is empty, change it to:
mysql.default_socket = /var/run/mysqld/mysqld.sock
The previous step should be written hereQueryTo the file, set it according to your situation. At this point, the PHP configuration has been modified. If it is CLI (command line) mode or CGI mode, it will take effect immediately. If it is FASTCGI mode, you need to restart the fastcgi process.
The above is the detailed content of Detailed explanation of the problem that MySQL cannot connect to the database through localhost. For more information, please follow other related articles on the PHP Chinese website!