MySQL – Cannot Connect via ‘localhost’, Only 127.0.0.1

localhostMySQLPHP

this is somewhat of a mystery to me. The only way I can connect to MySQL is if I call it via "127.0.0.1" … for example, my PHP connect script will NOT work with localhost

I'm running Mac OS X Lion, built-in apache2, MySQL, PHP, phpMyAdmin

mysqladmin:

count                             0
debug-check                       FALSE
debug-info                        TRUE
force                             FALSE
compress                          FALSE
character-sets-dir                (No default value)
default-character-set             auto
host                              (No default value)
no-beep                           FALSE
port                              0
relative                          FALSE
socket                            (No default value)
sleep                             0
ssl                               FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-verify-server-cert            FALSE
user                              (No default value)
verbose                           FALSE
vertical                          FALSE
connect-timeout                   43200
shutdown-timeout                  3600
plugin-dir                        (No default value)
default-auth                      (No default value)

Best Answer

MySQL will try to connect to the unix socket if you tell it to connect to "localhost". If you tell it to connect to 127.0.0.1 you are forcing it to connect to the network socket. So probably you have MySQL configured to only listen to the network socket and not to the file system socket.

What exactly is wrong with your unix socket is hard to tell. But I recommend you to read this page on the MySQL reference guide. This should help you.

UPDATE: Based on the updated question: The parameter "socket" should be something like this: "/var/lib/mysql/mysql.sock". This page in the Reference Manual has some more information.

Here you have the beginning of my /etc/my.cnf file:

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

Your file should be similar. Then your problem should be solved. Don't forget to restart the MySQL server before you test it.