Warning: PDO::__construct(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

Viewed 49414

My code was working all fine yesterday and today it suddenly just don't want to connect to my database. I have changed no settings on it or on the code and I haven't updated any software either. All I do is this:

new PDO('mysql:host=localhost;port=3306;dbname=test', 'username', 'password');

And I get a nice exception message saying this:

Warning: PDO::__construct(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in ...

The thing is: I'm clearly not trying to connect using a unix socket but using TCP/IP. What am I doing wrong? Is there something I'm missing here?

Thanks for any help.

5 Answers

From the PHP documentation about connection to MySQL using PDO: PDO_MYSQL DNS

The note at the very end says:

Unix only:

When the host name is set to "localhost", then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against libmysql then the location of the socket file is at libmysql's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.

So in order to fix this you would have to properly configure in php.ini the location of your mysql.sock

  1. Find your mysql.sock file. Common locations:

    • /tmp/mysql.sock
    • /tmp/mysql/mysql.sock
    • /var/mysql/mysql.sock
    • or if you use MAMP or LAMP look for inside the tmp folder for mysql
  2. Edit your php.ini file and properly set the value for pdo_mysql.default_socket

  3. Restart your Apache server to pickup the changes in the php.ini file

Related