Solution to Unsuccessful Connection of Mysql with localhost in PHP

  • 2021-07-13 04:50:24
  • OfStack

Find a problem

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

So I wrote an PHP page to test the connection database:

$mysql = mysql_connect('localhost','root','');

Open the http://localhost/test.php test

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

Check that the environment is normal

Thought that the database did not start, so look at the process under 1, MySQL in the process, restarted under 1 MySQL.

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

You can connect to the database directly used/usr/local/php5/bin/php/web/test. php
apache has also been restarted, and one sample is invalid

Doubt: Why did the web page fail and the command succeed

This is depressing, using the php command to execute directly on the success, through the web page to execute on the failure. Is it caused by apache? After searching a lot of information on the Internet, no solution was found, and the problem of recompiling and installing apache remained.

Successfully changed localhost to 127.0. 0.1

After changing localhost to 127.0. 0.1, the connection succeeded, and began to fall into a thinking dilemma: localhost failed but 127.0. 0.1 succeeded?

ping localhost address is 127.0. 0.1. That's right

Open hosts to join


127.0.0.1 qttc

When using qttc, the host connection is normal, but localhost is not recognized.

Different connection modes of localhost lead to

In order to understand the PHP connection to the database, the host filled in localhost and other differences read a lot of information, and finally learned:

mysql will use unix domain socket connection when the host is localhost
When the host is 127.0. 0.1, mysql will be connected by tcp
This is a feature of the linux socket network, and the win platform will not have this problem

Solution

Add in the [mysql] section of my. cnf

protocol=tcp

Save and restart MySQL, problem solved!


Related articles: