Connect MySQL through localhost not working but 127.0.0.1 is working

我怕爱的太早我们不能终老 提交于 2019-12-01 14:54:16

问题


OS: Ubuntu 14.04 LTS

php version control : phpbrew

php version : 5.5.10

I pinged localhost which resolved to 127.0.0.1.

This indicates that my host (/etc/hosts) file is correct.

127.0.0.1 localhost

Whenever I try connecting to MySQL using a php script like the one below it doesn't work and gives me the error: no such directory.

    //connect to the database
    mysql_connect("localhost","root","password") or die(mysql_error());

However, when I connect via 127.0.0.1 it will work

 //connect to the database
        mysql_connect("127.0.0.1","root","password") or die(mysql_error());

Additionally, my phpmyadmin does not work when logging in using "localhost" i had to change the file to add 127.0.0.1 option during log on.

How can I use localhost to connect to the MySQL database?


回答1:


PHP is still trying to use the default socket location. This problem can appear if you have moved the MariaDB/MySQL folder from /var/lib/mysql to another location. In order to solve the problem you have to define the new socket's location in the /etc/php.ini file.

mysqli.default_socket =/newDBLocation/mysql/mysql.sock

Watch out, depending on which driver you use, you may have to specify the pdo_mysql.default_socket=!

In order to check your current directory run the following command in mysql:

select @@datadir;



回答2:


In many cases localhost is a hint to use the UNIX socket to connect to the MySQL server process, where 127.0.0.1 forces a TCP connection. Sometimes the UNIX socket is in an unexpected place, or simply isn't accessible, which results in the "file not found" error.

The socket is typically something like /tmp/mysql.sock or could be in some other place depending on your distribution and how much you've customized it.

Keep in mind that access via UNIX socket, which is local to the server by definition, and TCP are controlled by two different rules. localhost in a GRANT refers to UNIX socket. % or some specific host name refers to remote via TCP.




回答3:


The answer to this problem was that in the my.cnf located within

/etc/mysql/my.cnf

the line was either

bind-address = 127.0.0.1 

or

bind-address = localhost 

it should have been

bind-address = 0.0.0.0

which will allow all connections



来源:https://stackoverflow.com/questions/31413728/connect-mysql-through-localhost-not-working-but-127-0-0-1-is-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!