PHP PDOException MySQL socket error FAQ: What is the PHP PDOException SQLSTATE MySQL socket error, and how do I fix the problem?
Every time I work with a new web hosting company, I keep running into one variation or another of this PHP MySQL socket error. It's pretty darned annoying, but at least I know how to fix it now.
In short, if you try to access a MySQL database using the PHP PDO library, such as with Drupal 7, which is what I just did, you may get an ugly MySQL socket error that looks like this:
PDOException: SQLSTATE[HY000]  Can't connect to local MySQL server through socket '/home/lib/mysql/mysql.sock' (2) in drupal_is_denied() (line 1779 of /home/al/html/includes/bootstrap.inc).
What this has always meant for me is that I'm trying to access my MySQL database host with the name "localhost". When PHP sees this, it looks for a MySQL socket wherever the PHP configuration file says the socket should be.
PHP PDO MySQL socket error - Solution
The solution to this error message is simple: Change "localhost" to the IP address "127.0.0.1". For some reason when PHP sees this IP address it doesn't attempt to access a local socket, and instead assumes that it should use a network connection to your MySQL database server.
To repeat, in your PHP configuration file (which in my case was a Drupal configuration file), change from this:
$host = 'localhost'
$host = '127.0.0.1'
If that doesn't work, please check my PHP MySQL can't connect socket error tip, which discusses this in a little more depth.
There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.