Fix "Error establishing a database connection" in WordPress
This error means WordPress could not reach its database: wrong details in wp-config.php, the database service stopped, a full disk, or damaged tables. Check them in this order.
Last updated:
Step 1: check the connection details
Open wp-config.php in the site folder and check DB_NAME, DB_USER, DB_PASSWORD and DB_HOST. This error is common after moving a site or changing the database password. DB_HOST is localhost in most cases.
Try connecting by hand with the same details. If it fails, the details are wrong or the service is stopped. If it works, the problem is elsewhere.
$ mysql -u DB_USER -p -h localhost DB_NAMEStep 2: is the database service running?
It is called mariadb or mysql depending on your server. If it keeps stopping by itself, read its log. The common cause on small servers is running out of memory, then a full disk.
$ sudo systemctl status mariadb $ sudo systemctl restart mariadb $ sudo journalctl -u mariadb -n 50
Step 3: check memory and space
The database will not start if the disk is full, and the system may stop it if memory runs out.
$ df -h $ free -m $ sudo dmesg -T | grep -i "out of memory"
Step 4: repair damaged tables
If wp-admin says tables need repair, add this line to wp-config.php and open example.com/wp-admin/maint/repair.php, then remove the line right after, because that page works without logging in.
$ define('WP_ALLOW_REPAIR', true);On shared hosting
Open MySQL Databases in cPanel or Databases in Plesk, and make sure the user is attached to the database with all privileges. You can reset the password there and write it in wp-config.php.
$ mysqldump -u DB_USER -p DB_NAME > backup.sql
