This bedeviled me today for a while, so I figured I’d share it here.
PHP will attempt to connect with a local socket instead of using TCP when ‘localhost’ is specified as the hostname, and this can have unpredictable results. Wordpress, for example, on a Mac, completely failed to connect to the database, even though phpMyAdmin, for example, with the same hostname, connected just fine, and manually cURLing localhost:3306 gave me back the expected “Got packets out of order” failure-blob, so I knew the server was up and on the usual port.
This is apparently solvable three ways. One: use 127.0.0.1 as your hostname, instead of localhost, because using the IP forces PHP to use TCP. You can also try and make sure that PHP’s settings look for the socket at the right place — /tmp/mysql.sock instead of the default /var/mysql/mysql.sock. The most fragile way is to symlink those two locations to each other.
I switched to specifying my local loopback IP and everything’s hunky-dory.