Fixing error 2002 for MySQL installation on Mac OS X

After you've installed MySQL on MacOS X, you will probably encounter this common error while trying to open a connection from a PHP script to your database instance:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'

This message tells you that PHP can't find the mysql.sock file into /var/lib/mysql/ directory.

Let's fix it.

First step (if you have not done it, yet) :
PHP should be looking for a php.ini file (and not php.ini.default) to load, so you need to rename php.ini.default to php.ini in /etc.
> cd /etc/
> sudo mv php.ini.default php.ini

Second step:
In Snow Leopard, mysql.sock file has been moved to /var/mysql directory (instead of /tmp directory).
You have two possibilities:

1. (SUGGESTED) create an alias in the location that PHP is looking for the real mysql.sock 
> sudo mkdir /var/mysql
> sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

 
2.  create a my.cnf configuration file in the /etc directory and save it with the following contents:
[client] socket = /var/mysql/mysql.sock
[mysqld] socket = /var/mysql/mysql.sock

and then

> sudo mkdir /var/mysql
> sudo chown _mysql /var/mysql


START or RESTART Apache and voila: les jeux sont faits!

Happy coding!