There are many reasons for this, so first check that MySQL/MariaDB is running properly, that you are using the correct credentials and that the the appropriate
user@localhost has access.
Also check you aren’t using
bind-address in your
my.cnf file if accessing from outside of the
localhost. These are things you will find with a google search.
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.
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
[mysqld] sections for the socket parameter. This is more likely to occur if you are using MariaDB for example.