Perfect solution to the problem that MySQL can't connect to the database through localhost
- 2021-07-09 09:25:40
Problem: The PHP program of one server cannot connect to the database through localhost address, but if it is set to 127.0. 0.1, it can connect normally, and it is also normal to connect to other database servers. The permissions of MySQL are set correctly, and the mysql command-line client can connect to the database normally.
Analysis: This is a typical case where socket is not set up correctly.
There are two ways to connect to an MySQL database: TCP/IP (the kind of port that is understood as 1) and Unix sockets (known as socket or sock as 1). In most cases, localhost can be used to represent native 127.0. 0.1, but when connecting with MySQL, the two cannot be mixed, and localhost and 127.0. 0.1 are set separately in permission settings in MySQL. When it is set to 127.0. 0.1, the system connects to the database through TCP/IP; When it is set to localhost, the system connects to the database through socket.
Solution: The first thing to see is where the socket socket file of the native MySQL is. The view command is:
mysqld --verbose --help | grep socket
The output shows the location of the socket file, for example, this server shows the location of the socket file
Then modify the php configuration file php. ini to correspond to it.
Find this item:
1 Generally speaking, this item is empty and changed to:
mysql.default_socket = /var/run/mysqld/mysqld.sock
Here you should write the file found in step 1, and 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, it is necessary to restart the fastcgi process for 1 time.