English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Perfectly Solve the Problem of Not Being Able to Connect to the Database via localhost in MySQL

Problem:A PHP program on a server cannot connect to the database through the localhost address, but if it is set to127.0.0.1It can connect normally, and it can also connect to other database servers normally. The MySQL permission settings are correct, and it can connect to the database normally through the mysql command-line client.

Analysis:This is a typical case where the socket is not set correctly.

There are two ways to connect to the MySQL database: TCP/IP (the kind of port commonly understood) and Unix socket (usually called socket or sock). In most cases, localhost can represent the local machine127.0.0.1, but when connecting to MySQL, the two cannot be mixed, and in the MySQL permission settings, localhost and127.0.0.1is also separately set. When set to127.0.0.1The system connects to the database through TCP/IP connection to the database; when set to localhost, the system connects to the database through the socket.

Solution: First, check where the MySQL socket socket file is on this machine, the command is:

mysqld --verbose --help | grep socket

The output shows the location of the socket file, for example: this server shows

socket      /var/run/mysqld/mysqld.sock

Then modify the php configuration file php.ini to correspond to it.

Find this item:

mysql.default_socket =

Generally, this item is empty, change it to:

mysql.default_socket = /var/run/mysqld/mysqld.sock

Here, you should write the file queried in the previous step, and set it according to your situation. At this point, the php configuration has been modified. If it is in CLI (command line) mode or CGI mode, it will take effect immediately. If it is in FASTCGI mode, you need to restart the fastcgi process.

This article, which perfectly solves the problem of MySQL not being able to connect to the database through localhost, is all the content that the editor shares with everyone. I hope it can provide a reference for everyone, and I also hope everyone will support and cheer for the tutorial.

You May Also Like