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.