Changing MySQL socket to fix 'Error Establishing a Database Connection' error in WordPress

When I work on WordPress sites, if I don’t do an undocumented trick, I can’t get WordPress to connect to the database. I get the ‘Error Establishing a Database Connection’ error.

If you’ve double-checked your wp-config.php settings to make sure the host, username, password and database match exactly, and you’re able to connect with the username, password and host on the command line, this trick might help you too.

It’s simple, append :/path/to/socket to your hostname like this:

define('DB_NAME', 'wordpress');
define('DB_USER', 'wordpress');
define('DB_PASSWORD', 'wordpress');
define('DB_HOST', 'localhost:/tmp/mysql.sock'); // my computer has the mysql socket on /tmp/mysql.sock

If you don’t know what your socket is, use the mysql command line tool to find it. Here’s how:

From your shell type this (obviously substituting in your username, host and database)
> mysql -u wordpress -p -h localhost wordpress

MySQL will start up and give you a prompt. At the mysql prompt type s (backslash + s). That will give you a screen full of status information like this:

mysql> s
mysql Ver 14.14 Distrib 5.1.45, for apple-darwin10.2.0 (i386) using readline 5.1

Connection id: 25
Current database: wordpress
Current user: wordpress@localhost
SSL: Not in use
Current pager: less
Using outfile: ''
Using delimiter: ;
Server version: 5.1.45 MySQL Community Server (GPL)
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: latin1
Conn. characterset: latin1
UNIX socket: /tmp/mysql.sock
Uptime: 3 days 13 hours 51 min 22 sec

Threads: 1 Questions: 532 Slow queries: 0 Opens: 48 Flush tables: 1 Open tables: 19 Queries per second avg: 0.1

The piece of information you’re looking for is the line that says UNIX socket: /tmp/mysql.sock. Put that in your wp-config.php and that will tell PHP how to talk to your database.

define('DB_HOST', 'localhost:/tmp/mysql.sock');

I hope that helps. If you have questions, leave them in the comments.