The PHP PDOException SQLSTATE MySQL can't connect socket error

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] [2002] 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/

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 "". 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'

to this:

$host = ''

If that doesn't work, please check my PHP MySQL can't connect socket error tip, which discusses this in a little more depth.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.