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
bind-address in your
my.cnf file if accessing from outside of the
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
[mysqld] sections for the socket parameter.