Madproject

Always know where your towel is.

Connect to MySQL using localhost instead of 127.0.0.1 on a MAC

For a long while now I’ve been connecting to MySQL on my development platform with 127.0.0.1 because for some reason localhost didn’t work.
Turns out it’s because 127.0.0.1 uses TCP/IP and localhost uses sockets.
The php.ini file points to the wrong place for the mysql.sock so all you have to do is change it, restart apache and voila!

  • Open php.ini: /private/etc/php.ini
  • Find the following line: mysql.default_socket = /var/mysql/mysql.sock
  • Replace with: mysql.default_socket = /tmp/mysql.sock
  • Restart apache: apachectl restart
  • Happy days!

Note: If you don’t have a php.ini file, you need to copy the provided default called php.ini.default

sudo cp /private/etc/php.ini.default /private/etc/php.ini

Thanks to Blog.Andrei.MD for the info.

8 comments for “Connect to MySQL using localhost instead of 127.0.0.1 on a MAC

  1. May 4, 2012 at 07:18

    Yes! First result for “mac mysql 127.0.0.1” – am starting a new job next week and can’t be messing about changing config files from localhost to 127.0.0.1 all the time – have been meaning to look at this for ages – ta!

  2. December 20, 2012 at 22:50

    This worked fantastically, I’ve been having to change database files all the time.

  3. May 27, 2013 at 08:20

    Thank You so much. I was very tired of “127.0.0.1” again, and again. My first thought was /etc/hosts/ but no…

  4. Stephen
    June 15, 2013 at 15:06

    This had been bothering me for ages but I’d never worked out why or how to fix it… Thanks for the solution!

  5. Donovan Rittenbach
    August 1, 2013 at 05:14

    Ay chihuahua! I have been looking for this solution for years. Finally I have found the grail. Now I can return to my fair lady and claim her as mine. : ) Thanks!

  6. October 26, 2013 at 03:37

    Another solution is to have a symlink

    sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

    Found there : http://www.coolestguidesontheplanet.com/downtown/get-apache-mysql-php-and-phpmyadmin-working-osx-109-mavericks

    😉

    • Joshua Jacobson
      July 29, 2014 at 20:53

      @OVinz, thanks for your comment. I had to switch the order, and the socket path is different for mysql installed through MAMP:
      sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

  7. January 28, 2015 at 12:06

    Thanks for the tip! It worked like a charm.

Leave a Reply

Your email address will not be published. Required fields are marked *