"Error establishing a database connection" may be caused by many different reasons and the worst thing about this error is that you don't get any indications about what went wrong. In this post we will list four of the most common reasons and solutions.
First of all you need to check if you get the same error on the back-end of the website, try accessing the admin area if you get the same error then you can skip this method and go to the next one, if you get a different error message something like "One or more database tables are unavailable. The database may need to be repaired" follow the steps below.
Database repair is disabled by default, so to repair your database you need to add one line of code right after define('WP_DEBUG', false); in your wp-config.php
Once you have modified wp-config.php try accessing /wp-admin/maint/repair.php on your website, click either on Repair database or Repair and Optimize database depending on what's most suitable for you.
Don't forget to remove the line you added in wp-config.php. If this method didn't help you solve your problem keep reading as you may find a solution that will work for you.
It may be that your database credentials are entered incorrectly or may have been modified recently. The first step is to login to your cPanel and open MySQL Databases so you can check if the user and the database are connected, check also the privileges of the user. Now change the password of the user, use a really strong one and remember the database name and the username. Open wp-config.php that is in the WordPress root folder and update the password, but also check if the database name and the username from the file matches the ones on the server.
If this didn't help you as well, keep reading as there are more solutions to this problem.
The first step before doing anything you need to backup all of your files. Go to WordPress.org and download the latest version of WordPress, once downloaded unzip it and delete the wp-content folder and wp-config.php if it exists. Upload all files to the server either using FTP client or cPanel's File Manager.
If you use a shared server to host your website it might be that your server is overloaded. There are many reasons why this might happen, the most common is that there is a great increase in traffic that your server cannot handle, however even if you don't have an increase in traffic it can be that another hosting company's client has overloaded the database since it is a shared hosting. The good thing is that in this case the error doesn't last a long time, but if you see the problem more than a few times contact your hosting company. You should try using a caching plugin such as WP Super Cache, if it doesn't help and the problem persists you should change your hosting plan to Virtual Private Server (VPS).