Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot connect to mysql with 127.0.0.1

With the following code I can connect to mysql: mysql_connect("localhost","username","");

But if I change localhost to 127.0.0.1 I get the following error:

Can't connect to MySQL server on '127.0.0.1' (13)

Why doesn't it work with 127.0.0.1?

like image 315
user16948 Avatar asked Apr 27 '12 09:04

user16948


People also ask

Why can I not connect to localhost MySQL?

Here are some reasons the Can't connect to local MySQL server error might occur: mysqld is not running on the local host. Check your operating system's process list to ensure the mysqld process is present. You're running a MySQL server on Windows with many TCP/IP connections to it.

Why MySQL database is not connecting?

Make sure that you have a file named user. MYD in the mysql database directory. If not, initialize the data directory. After doing so and starting the server, you should be able to connect to the server.


2 Answers

localhost is special cased and uses UNIX sockets instead of TCP/IP. 127.0.0.1 doesn't get that special handling.

See the documentation:

On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option.

If it doesn't work when you use TCP/IP then the database probably isn't listening on the network. This is generally a good thing as it enhances security (not that listening on 127.0.0.1 exposes any problems, but listening on all interfaces gives more opportunity for attacks).

If you really want to allow connections via the network, then see skip-networking.

like image 148
Quentin Avatar answered Oct 02 '22 14:10

Quentin


have you got an entry in your hosts file mapping 127.0.0.7 to localhost?

like image 39
Sachin Kainth Avatar answered Oct 02 '22 12:10

Sachin Kainth