Warning: mysql_connect(): No such file or directory

On January 27, 2015, in PHP, by Anuj Gakhar

I’ve been trying to setup a local PHP/Mysql app today and came across this issue with the database connection.

Warning: mysql_connect(): No such file or directory

The connection parameters I’ve been using were as follows :-

define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "my_db");

Turns out, the fix was quite simple. Change the above code like below and problem solved!

define("DB_HOST", "127.0.0.1");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "my_db");

The reason is that “localhost” is a special name for the mysql driver making it use the unix socket to connect to mysql instead of the a tcp socket.

There are potentially other solutions for this problem as well. On OSX, the Mysql socket file is sometimes not properly located. You may have a socket (appearing as a zero length file) as /tmp/mysql.sock or /var/mysql/mysql.sock but 1 or more apps is looking in the other location for it. So creating a symbolic link to the right file helps. More details can be found on the SO question.

In my case, I thought changing localhost to 127.0.0.1 did the trick and seemed like the easiest solution. That may not always be the solution though, especially when the Mysql host is not local.

 

2 Responses to Warning: mysql_connect(): No such file or directory

  1. savaj says:

    for the write database connection like this my problem hasbeen solved
    @ mysql_connect
    and @mysql_selectdb replace with this on your syntax…

  2. mava says:

    Tnx!
    That solved my problem!

Leave a Reply

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 445 other subscribers

© 2011 Anuj Gakhar
%d bloggers like this: