Wordpress Error Establishing a Database Connection : Connecting To Database

How to Fix the Wordpress Error Establishing a Database Connection :  Connecting To Database


What Causes This Error?

While the meaning of the error message is clear, the reasons behind its occurrence often aren’t.
There are many reasons why your website could be having trouble connecting to your database, but they generally fall into three categories:
  1. Your login credentials for your database are wrong. Your database uses separate login credentials (username and password). If those credentials have recently been changed, your website won’t be able to access the database with the old credentials.
  2. Your database is corrupted. Any number of things could cause your WordPress database to become corrupted, from uploading a bad plugin, to lightning strikes to the server (seriously — though luckily that isn’t too common).
  3. The server that hosts your database is down. Your database’s server may be down due to a problem or error on the part of your web hosting company, or you could be experiencing a big traffic spike that your server just couldn’t handle.
So with all these possibilities, how can you narrow down the problem and fix it?

Troubleshooting “Error Establishing a Database Connection”

1. Determine where the error is occurring

Can you see your website normally, but get the error when trying to access wp-admin? Or maybe your website is down, but you’re getting a slightly different error when you try to login: “One or more database tables are unavailable. The database may need to be repaired.”
These are signs of database corruption.
WordPress has a built-in way to attempt to repair your database, but you’ll have to enable this feature first. To do so, you’ll need to access your wp-config.php file, which contains your WordPress installation settings and configuration.
You can find wp-config in the your root WordPress file directory. You can access it by logging into your cPanel, selecting File Manager, and navigating to the folder where you installed WordPress.
Once you have wp-config open, add this line of code to the bottom:
define( 'WP_ALLOW_REPAIR', true );
This line will enable you to optimize and repair your database by navigating to www.yourwebsite.com/wp-admin/maint/repair.php (just replace “yourwebsite.com” with your actual URL).
You should see the above screen with two options to repair, or repair and optimize, your database. Feel free to choose either; just note that optimizing will take longer.
Please note that this database repair page is not secure; anyone can access that URL without having to login. Once you’re done repairing your database, be sure to remove the line of code you added to wp-config. This will disable access to the repair page and prevent anyone else from messing with your database.
(Just as a side note, there are other ways available to repair and optimize your WordPress database, including via PHPMyAdmin in cPanel. I wrote a bit about it here: Cleaning Up Your WordPress Database To Optimize Your Website’s Performance)
Keep wp-config open for now until you’re certain the error is resolved and your website is working again. If you’re still getting the same error message, you’ll need wp-config open for the next step.
If this doesn’t apply to you, or if it didn’t work, move on to the next step to continue troubleshooting.

2. Check your database login settings in wp-config

If the above step didn’t work or didn’t apply to you, then the next thing you can do is take a look at your database settings in your wp-config file.
Wondering how your database login credentials could have suddently stopped working? Things like switching hosting companies or changing anything about your database name or user information could cause the error if your wp-config file wasn’t updated to the new information.
You may still have the wp-config file open from the last step. If not, log into your host’s cPanel and open the File Manager. Navigate to the directory where you installed WordPress, and look for a file called wp-config.php. Go ahead and open that for editing.
You’ll see the login credentials for your database, probably near the top of the file. It should look something like this:
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME''database_name_here' );
/** MySQL database username */
define( 'DB_USER''username_here' );
/** MySQL database password */
define( 'DB_PASSWORD''password_here' );
/** MySQL hostname */
define( 'DB_HOST''localhost' );
As you can see, there are four pieces of information WordPress needs to access your database:
  1. The name of the database (“DB_NAME”)
  2. The login username (“DB_USER”)
  3. The login password (“DB_PASSWORD”)
  4. The database host (“DB_HOST”)
If any one of these values is incorrect, WordPress will not be able to connect to the database.
One way to check on your database outside of WordPress is by using PHPMyAdmin, a tool for accessing and editing MySQL databases. PHPMyAdmin is included with most hosting plans, and you can find it in your cPanel dashboard.
Warning: Be very careful using PHPMyAdmin, since you’ll be dealing directly with your site’s database.
Once you’ve logged in to PHPMyAdmin, you will see a list of databases on your server in the left-hand column. Click on the one that matches the name in your wp-config file (it will be the value after DB_NAME, where it says “database_name_here” in the above sample code).
(Don’t see any databases? Contact your hosting company, since the entire problem may be an issue with your server.)
After clicking on your database name, you’ll see the main screen populate with the names of the tables in your database. To make sure this is the correct database, you can find the table named “wp_options” and click on the ‘Browse” option next to it. You should see your website’s name, URL, and your other general settings here. Now you know whether or not you have the correct database name in your wp-config file. If it’s not correct, go ahead and fix it in wp-config.
Now let’s check on the username and password.
There are a few ways to do this, some more convoluted than others. I’ll give you two options.
  1. You can either create a simple .php file to test whether you are able to connect to your database with the credentials in your wp-config file, or
  2. You can just create a new user and password, and update your wp-config file with the new info. You’ll have to do this if #1 fails, so you might just want to skip to this step.
Option 1: Test your existing credentials.
Create a file in your WordPress directory called something like testconnection.php (the name doesn’t matter; just the .php extension). Paste the following code:
<?php
$test Connection = mysql_connect('localhost''root''password');
if (!$testConnection) {
die('Error: ' . mysql_error());
}
echo 'Database connection working!';
mysql_close($testConnection);
?>
Once you’ve created that file, just navigate to the URL of the file in your browser (e.g. your site.com/testconnection.php). You’ll see either a successful connection message, or an error with more details.
If the username and password isn’t working, we can just create a new one.
Option 2: Create a new database user and password.
We can do that using a different tool available in cPanel called “MySQL® Databases.” Go ahead and click on that, then scroll down to the heading: MySQL Users: Add New User.” Choose a username and strong password, and make note of them for your wp-config file. Click “Create User.” Now scroll down to the heading “Add User To Database,” and choose your new username and your WordPress database, and click “Add.” Update your wp-config file with the new username and password.
Now your database name, username, and password are all correct. That just leaves DB_HOST.
In most cases, this value will be “localhost,” but it depends on your host’s settings. WordPress has a list of common hosts with their DB_HOST values on their website. If your host isn’t listed there, you can contact your hosting company to ask what value to use.

3. Still getting the error message? Check with your hosting company

If you’ve followed the above troubleshooting steps and your website is still down, it could be a problem on your host’s end. Contact your web hosting company’s support and give them all the details of the error and the troubleshooting actions you’ve taken, and they may be able to help you determine the cause of the error.

______________________________________________________________________
______________________________________________________________________
2nd Method

What Does ‘Error Establishing a Database Connection’ Actually Mean?

Instead of being saved in specific files, the content of WordPress posts and pages is saved in a database that WordPress needs to reference each time it serves/generates a webpage. When a post gets viewed, for example, WordPress finds the database host, connects to its database, finds the WordPress posts table within that database, and looks up the content it’s trying to load. In short, the infamous ‘error establishing a database connection‘ means that WordPress cannot find this database.
Why is this such a big issue? Well, in addition to the content of posts and pages, WordPress also stores a whole heap of other essential information in its database — such as its main settings, your user data, your selected theme, your widget settings, data for your active plugins, and so on. If WordPress can’t access any of the information within its database, it has no way of loading your website.

What Is the Cause of a Database Connection Issue?

There are a number of issues that could cause a communication problem with the database. Let’s create a shortlist, and delve deeper to better understand (and solve) each problem:
  • Incorrect database credentials (username, password, host, database)
  • Corrupted files
  • Corrupted database
  • Database server is overloaded or malfunctioning

But first…

While the processes I’ll be looking at aren’t dangerous, it’s always a good idea to have a backup — just in case. If you’re already using a tool such as VaultPress — which I heartily recommend — you’re already backed up and good to go.
There are lots of plugins that can back things up for you, but if you’re already locked out of WordPress you won’t be able to use them. In this case, you’ll need to use your cPanel or other hosting management software to make a complete backup.
If you don’t know how to do this, talk to your hosts — most of them will have a backup solution of sorts. Be sure to back up your database, as well as the files on your server, since it’s the database that contains all the critical information for your website.

Fixing Database Connection Issues

I’ve written the above list in order of likelihood, based on my experience, but you can start from the bottom and work up if you prefer. That said, if you don’t have a direct line (or chat support) with your host, it will be difficult to tell whether or not a database server is overloaded or malfunctioning on their end, because from your end the symptoms are indistinguishable. In any case, let’s take a look at each of the causes and see what we can do to fix things.

INCORRECT DATABASE CREDENTIALS

This is one I see quite often. If you see the ‘error establishing a database connection’ message when setting up a brand new WordPress install, then this is almost certainly the culprit. To connect to its database, WordPress needs four key pieces of information:
  • Database host
  • Database username
  • Database password
  • Database used
All this information should be given to you (if not actually entered on your behalf) by your host. However, if you’re using a more flexible setup (i.e. not a one-click type of install), you should check your username, password, and the name of your database. Your best bet is to copy and paste all the data directly from the medium in which it was given to you. (Note: Passwords can sometimes have dashes or periods at the end that aren’t normally selected.)
If you’ve recently switched hosts, make sure to double-check the ‘database host’ details. In many cases, this will be ‘localhost’ (Bluehost, HostGator). It should be noted that many hosts use an IP Address (SiteGround) or even a completely different URL (DreamHost). If you’re unsure about any part of this you should either contact your host and ask them directly or look at their online knowledgebase (if they have one).
On a new install, you’ll likely be presented with fields in which to enter this information as you go through the standard WordPress on-screen setup routine. In many cases, you can even go back and fill out this information again. If not, you’ll need to download, edit and then (using an appropriate FTP client) re-upload the configuration file located in the WordPress root directory (called wp-config.php). Be sure to only edit this file using a text editor, of course. The database connection details are near the top, and look something like this:
1
2
3
4
5
6
7
8
9
10
define('DB_NAME', 'database_name');
/** MySQL database username */
define('DB_USER', 'database_user');
/** MySQL database password */
define('DB_PASSWORD', 'database_password');
/** MySQL hostname */
define('DB_HOST', 'database_host');
Simply change the values in the second set of parentheses to modify your connection details to the correct values, and you should be up and running in no time. If, however, you’ve checked and double-checked all of these details, and you’re still getting the same error, then it’s time to move on to the next issue: Corrupted files.

CORRUPTED FILES

In some cases, users have reported that re-uploading the core WordPress files sometimes fixes the error — the exact reason why this can work may seem like a mystery, but, in many cases it’s to do with either resetting file permissions or replacing corrupt core files. (Note: Be sure not to overwrite either the config.php file, which contains crucial setup information, or the wp-content directory, which holds your themes, plugins and media, and remember to always back up before modifying or replacing anything.)
To get this done, you’ll need to download a fresh version of WordPress from WordPress.org and unzip the package on your computer. Go into the unzipped folder, and delete both the config.php file and the wp-content folder to be sure you don’t accidentally replace the ones on your live server. Once these have been deleted, open an FTP client and prepare to upload the remaining files to your WordPress root folder.
Assuming nobody’s ever made dodgy modifications to your WordPress core files, you should now be able to safely overwrite all of these files on your live server — making sure not to accidentally overwrite the wp-config.php file or the wp-content folder, of course.

CORRUPTED DATABASE

A good indication of a corrupted database is if the website front end works, but the backend doesn’t (or vice-versa). You may also see an error message telling you that some database tables cannot be found. Luckily, WordPress contains a tool that can help you repair a corrupted database. You’ll need to download your wp-config.php file (which you’ll find in the root directory of your WordPress install) and add the following line:
1
define( 'WP_ALLOW_REPAIR', true );
Once you’ve re-uploaded it, you should be able to access a special database repair page on your site by going to http://yoursite.com/wp-admin/maint/repair.php (substitute yoursite.com with your actual domain). You should see a screen displaying two options: ‘Repair Database’ and ‘Repair + Optimize Database’.


Although choosing either option should be fine, I’d recommend choosing only to repair the database. As a programmer, I’ve learned that even the seemingly irrelevant can cause unpredictable issues. I don’t see how also performing an optimization could ruin things, but it’s better to be safe than sorry in these situations. At the very least, optimizing the database as well as trying to repair it will almost certainly take quite a bit longer — and getting the database up and running should be the priority.
Once this has been done, be sure to go back into wp-admin.php and remove the above-mentioned line of code from the file. The repair page is not hidden and is not secure; it will remain publicly accessible for as long as that piece of code exists in the config file.

DATABASE SERVER IS OVERLOADED OR MALFUNCTIONING

Malfunctioning and overloaded servers are very difficult to differentiate without either having access to advanced hosting tools or talking to your hosting company. If you suspect one of these is happening and your host has real-time telephone or chat support, then your best bet is to ask them what’s going on directly.
If you’re using a shared server (meaning you have to share the server’s resources with a large number of other people), it can be hard to tell whether the cause of the error is because of an overload or a malfunction. In some cases, instead of a malfunction, it may actually be because another site on the same server is overloading the database. In other words, even if you have only a very small site with no sudden surges in traffic, it could be experiencing an overload caused by someone else’s website. This is a lot less likely to happen with a VPS or a managed WordPress hosting setup.
The good news is that both these issues usually resolve themselves within a relatively short time. If a database physically malfunctions, your webhost will almost always move to replace it as soon as their systems indicate the need to do so — and if a database goes down because of an overload, it will usually automatically reboot and be up and running again within a matter of minutes. If, however, this has happened a number of times, alert your hosts and have them investigate as soon as possible.
If your website is on a shared server and your traffic is rapidly increasing, you may start to experience database connection issues as you start to overload the server. Such errors will usually resolve themselves, but will happen again if your website continues to experience surges in traffic. In such cases, if you aren’t already doing so, using a good caching plugin, such as W3 Total Cache, WP Super Cache or WP Rocket may well alleviate further issues.
That said, the easiest way to solve this issue is to prevent it from happening at all.

Managed WordPress Hosting

While not a solution per se, moving over to a managed WordPress hosting package could save you a lot of headaches if you’re already starting to see these types of errors. Managed WordPress hosting is less flexible from a features point of view, but, if all you need is to be able to run WordPress, it can be an excellent option. (This very site runs on such a service.) WordPress-specific managed hosting is tailored to running WordPress as efficiently and quickly as possible. The hardware, the server software, and the customer care representatives –just about everything, in fact — are geared towards (and optimized for) WordPress!
The downsides of this type of hosting are not being able to access your server via SSH, and not being able to install other scripts outside WordPress (i.e. you can run WordPress and nothing else). Additionally, most managed WordPress hosts will prohibit you from using certain plugins that have been deemed either substandard and/or unsuitable for their systems.
If you’re interested in managed WordPress hosting, take a look at the options. Some of the best are those offered by WPEngine (arguably the leader in the managed WordPress hosting arena), Kinsta (great for large businesses) and Flywheel (geared towards designers and agencies).

Tag: 
error establishing a database connection cpanel, error establishing a database connection chrome, error establishing a database connection wordpress localhost xampp, how to fix error establishing a database connection, error establishing a database connection xampp, error establishing a database connection mamp, error establishing a database connection godaddy, error establishing a database connection wordpress ubuntu.

Comments