SoFunction
Updated on 2025-03-10

Solution to unsuccessful connection to Mysql using localhost in PHP

Discover problems

Yesterday, when I was helping my colleague compile and install Linux environment, I encountered a problem:
The WEB server is apache and the database is MySQL.

So I wrote a PHP page for testing the database connection:

Copy the codeThe code is as follows:
$mysql = mysql_connect('localhost','root','');

Open http://localhost/ test

Tip: Can't connect to local MySQL server through socket...

Check the environment is normal

I thought the database was not started, so I checked the process. MySQL restarted MySQL in the process.

Use mysql -u root -p to enter the MySQL operation interface

Directly use /usr/local/php5/bin/php/web/ to execute to connect to the database
Apache has also restarted, it is also invalid

Question: Why the web page failed, but the command execution succeeded

Now I feel depressed. I will succeed if I use the php command to execute directly, and if I fail to execute through the web page. Could it be that apache caused it? I searched for a lot of information online but couldn't find a solution. The problem of recompiling and installing apache is still there.

Change localhost to 127.0.0.1 successfully

After changing localhost to 127.0.0.1, the connection was successful and began to fall into a dilemma of thinking: localhost failed 127.0.0.1 but succeeded?

ping localhost address is 127.0.0.1, yes

Open hosts to join

Copy the codeThe code is as follows:

127.0.0.1 qttc

It is normal to use qttc when connecting to the host, but I don’t recognize localhost.

The localhost connection method is different, resulting in

In order to understand the difference between PHP and other databases, the host read a lot of information and finally learned:

When the host is filled in as localhost, mysql will use unix domain socket connection
When the host is filled in at 127.0.0.1, mysql will use tcp to connect
This is a feature of Linux socket network, and the win platform will not have this problem

Solution

Added in the [mysql] section

Copy the codeThe code is as follows:
protocol=tcp

Save and restart MySQL, the problem is solved!