Image for post
Image for post

PHP database can’t connect to localhost but 127.0.0.1 works

There are many reasons for this, so first check that MySQL/MariaDB is running properly and that you are using the correct credentials.

The best test is to use the mysql client from the same server that PHP is running from.

mysql -u <username> -p <database name>

Also check you aren’t using skip-name-resolve and bind-address in your my.cnf file if accessing from outside of the localhost.

Apart from this one other reason why 127.0.0.1 will work and localhost will not work is if you are using something other than the default socket=/var/lib/mysql/mysql.sock location in your my.cnf configuration so check for that.

If that is the case, you’ll need to update the relevant default_socket= parameter in php.ini (for each driver) to match that socket – see the entries under my.cnf [mysql] and [mysqld] sections for the socket parameter.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store