Home > Article > Backend Development > Solution to unsuccessful connection to Mysql using localhost in PHP, localhostmysql_PHP tutorial
Problem found
When I was helping my colleagues compile and install the Linux environment yesterday, I encountered a problem:
The WEB server is apache and the database is MySQL.
So I wrote a PHP page to test connecting to the database:
Open http://localhost/test.php to test
Tips: Can't connect to local MySQL server through socket...
Check that the environment is normal
I thought the database was not started, so I checked the process. MySQL was in the process and restarted MySQL.
Use mysql -u root -p to enter the MySQL operation interface
Directly use /usr/local/php5/bin/php /web/test.php to connect to the database
I also restarted apache, but it still doesn’t work
Doubtful point: Why the web page failed to execute but the command executed successfully
I feel depressed now. If I execute it directly using php command, it will succeed, but if I execute it through the web page, it will fail. Is it caused by apache? I searched a lot of information on the Internet but couldn't find a solution. The problem still persists after recompiling and installing apache.
Changed localhost to 127.0.0.1 successfully
After changing localhost to 127.0.0.1, the connection was successful. I started to fall into thinking dilemma: localhost failed but 127.0.0.1 succeeded?
ping localhost address is 127.0.0.1, yes
Open hosts and join
Different localhost connection methods cause
In order to understand the difference between the host filling in localhost and others when connecting to the database in PHP, I 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 as 127.0.0.1, mysql will use tcp to connect
This is a feature of the Linux socket network. The win platform will not have this problem
Solution
Add
in the [mysql] section of my.cnf
Baidu HI me
Database password Correct?
$mysql=mysql_connect("localhost","username","password");
if($mysql){
echo "Database connection successful";
}else{
echo "failed";
}
Is mysql support not enabled?
MySQL is no longer built-in support starting from php5. You need to set the php configuration file php.ini yourself to enable the mysql extension.