Unable to connect to MySQL from PHP (on Mac OS X)
Friday, June 13th, 2008When I tried to connect to MySQL from PHP, using mysql_connect, it gives me the “Can’t connect to MySQL through socket” error. And I am definitely sure, I added the user into MySQL, and had the correct password.
mysql_connect('localhost', 'username', 'very_encrypted_password');
The thing is, it works if I use 127.0.0.1 instead of localhost, strange..
MySQL:
$ mysql --version mysql Ver 14.12 Distrib 5.0.51a, for apple-darwin9.2.2 (i686) using EditLine wrapper
PHP:
$ php --version PHP 5.2.5 (cli) (built: Mar 4 2008 22:57:15)
After asking for help from Colin, who gave me a head start and some google’ing, I found a solution.
Quoted from the site [1]:
One problem that has come about with MySQL and Leopard is the location of the mysql.sock file. Previously, the default location for this file was in the /tmp directory. That location has now moved to the /var/mysql directory. PHP will look for it there. Unfortunately, the default location from the MySQL will still place it in the old location.
First of all, stop MySQL. Then open up /etc/my.cnf:
sudo vim /etc/my.cnf
In my case, I only had a couple of lines there:
[mysqld] binding = 127.0.0.1
Add these line, to the appropiate headings:
[mysqld] socket = /var/mysql/mysql.sock
[client] socket = /var/mysql/mysql.sock
Then, create the directories and set the proper permission:
sudo mkdir /var/mysql sudo chown _mysql /var/mysql
Finally, restart MySQL, and try it out!
ref: