I ran into an interesting problem with PHP on my Mac today. I have been dealing with this issue for a while where connecting to MySQL with PHP only seems to work if I use 127.0.0.1 as the hostname and not if use localhost. If I use localhost I was getting this errror:
Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/var/mysql/mysql.sock'
Well today I decided to figure out why this was happening. After researching a bit with Google I found a few references to the problem but no specific solution. Then I saw a mention of using sockets vs TCP/IP to make the connection. So it appears that when I specify the IP address (127.0.0.1), we are using TCP/IP to connect to MySQL. But if I use the hostname localhost then we are using sockets. Now apparently the MySQL default socket location is /var/mysql/mysql.sock but this is not the case on Leopard. The actual location on Leopard is /tmp/mysql.sock. There are several options to fix this and the easiest for me was to edit my /private/etc/php.ini and set the mysql.default_socket:
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
mysql.default_socket = /tmp/mysql.sock
Now, after restarting Apache, I can connect to MySQL with PHP using localhost instead of 127.0.0.1. If you are looking for other solutions in case you can't edit your php.ini, here are the other options:
Taken from here.
1. Create the /var/mysql directory (sudo mkdir /var/mysql) and then create a symbolic link from /tmp/mysql.sock to /var/mysql/mysql.sock (with: sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock).
2. Edit /etc/my.cnf adding the following lines:
[mysqld]
socket=/var/mysql/mysql.sock
[client]
socket=/var/mysql/mysql.sock
This will tell MySQL to create its socket where Leopard’s default PHP is looking for it. Next, you also need to create the /var/mysql directory and sudo chown mysql /var/mysql it or MySQL won’t start since it wont be able to create the socket.
3. Recompile php for your version of MySQL (a PIA, but not a terrible idea at all).
Of these #1 is easiest, but a bit of a hack. #2 isn’t to bad, but could cause issues with other MySQL clients that look for the socket in /tmp/mysql.sock. #3 is ultimately the best fix, but is clearly neither very fast nor particularly easy
That is some nice information. Thanks for the same.
Can you please put some blog regarding the Hands on Lab you conducted on PHP with Netbeans.
I will be waiting for the same.
Regards
JC
Posted by Jaspalsinh A. Chauhan (JC) on February 25, 2009 at 08:56 PM PST #