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 :-

[php]define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "my_db");[/php]

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

[php highlight=”1″]define("DB_HOST", "127.0.0.1");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "my_db");[/php]

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: