Home Blog WordPress Management Fix “Error Establishing a Database Connection” in WordPress

Fix error establishing a database connection in WordPress

Fix “Error Establishing a Database Connection” in WordPress

You visit your website and see the message “error establishing a database connection” instead of a working webpage. Where did the blog posts and other content go?

Don’t worry; your website data is most likely still safe. WordPress is just having issues accessing it.

To put you at ease, let’s first understand what’s happening.

WordPress stores all your website data related to users, posts, or general configuration in a database. It connects to this database to generate a webpage when someone visits the website.

If WordPress can’t connect to the database, it can’t access any data. Visitors see a database connection error in such situations. 

In this guide, we will walk you through some troubleshooting steps to help get your website working again.

Find out what is causing the database connection error

WordPress database connection errors are common, especially when installing, upgrading, and migrating a site. But there are other things that can cause this error to occur too.

A few reasons for a database connection error are incorrect database credentials, a corrupt database, and a lack of user privileges.

We can fix a database connection error quickly once we figure out the underlying cause.

Lucky for us, MySQL, the database management system WordPress uses, returns an error code when it encounters an error establishing a database connection.

In this section, we will manually make a database connection to get this error code. It will help pinpoint the exact issue.

Open your website’s wp-config.php file

WordPress uses the credentials stored in the wp-config.php file to establish a database connection. It auto-generates this file during installation.

You can usually find it in your site’s root directory.

The root installation directory is generally public_html or www, but it could be different for you. You can identify the root directory by its sub-directories like wp-admin, wp-content, and wp-includes.

Some setups might move the wp-config.php file to a different location or move its contents to a different file. They do this to improve the security of the wp-config.php file.

If the file isn’t in the root directory, check the parent directory.

After you find the file, open it in a plain text editor like Notepad or Visual Studio Code to see the database login credentials. Using a plain text editor will help prevent any encoding or formatting issues.

Find the current database credentials

You should check four credentials to see if they have the correct value:

  • Database name: This is the database where WordPress stores all your website data
  • Database user: This is the MySQL database username
  • Database password: This is the MySQL database password
  • Database hostname: This is the database host’s name, usually localhost

The wp-config.php file stores the value of these credentials in the following lines:

/** The name of the database for WordPress */
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’, ‘localhost’);

Search for these lines in the file and note the values for DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST.

We will use these values in the next section to perform our connection test.

Copy the database credentials to our script

You can download a simple WordPress MySQL database connection script we created to identify any database connection errors.

Once the download completes, extract its contents to get a file called wpdbtest.php.

This file has the following code near the top:

// Define database constants.
define( 'DBTEST_HOST', '#HOST' ); // REPLACE VALUE WITH YOUR HOST IP ADDRESS OR HOSTNAME.
define( 'DBTEST_DATABASE', '#DATABASE' ); // REPLACE VALUE WITH YOUR DATABASE NAME.
define( 'DBTEST_USER', '#DB_USER' ); // REPLACE VALUE WITH YOUR DATABASE USERNAME.
define( 'DBTEST_PASSWORD', '#DB_PASSWORD' ); // REPLACE VALUE WITH YOUR DATABASE USER PASSWORD.

Replace #HOST with the value for DB_HOST from the wp-config.php file.
Also replace #DATABASE, #DB_USER, and #DB_PASSWORD with the correct values for DB_NAME, DB_USER, and DB_PASSWORD respectively.

Now, save the file.

Upload the script to your root directory

After updating the wpdbtest.php file, upload it to your WordPress website’s root directory.

You can use an FTP client like FileZilla or the file manager in your web host control panel to upload the file.

We will use cPanel here for illustration.

Click on File Manager under the Files section and navigate to your WordPress site’s root installation directory.

Now, upload the wpdbtest.php file to the root directory.

Try connecting to the database server

You can now visit the URL https://your-website.com/wpdbtest.php in a web browser to execute the database connection script. Replace your-website.com with your actual domain name.
You will get an error message if the script can’t connect to the database. Here is the error we got:

Error code 1045 means we used the wrong credentials to connect to the database. We can connect successfully after we provide the correct credentials.

Here is a list of common MySQL database server connection codes:

Error CodeCauseResolution
1040Too many connectionsReduce the number of processes/applications using the database server or distribute the connections to other servers.
1041Out of memoryRestart the server to fix this issue, though it might happen again.
If so, increase the memory allocated to your database server.
1043Bad handshakeThis means the database connector you are using is using a different protocol than the one the server uses, so they cannot communicate.
This is a server configuration issue. Speak to your web host.
1044Access denied for user to the databaseThis means the database credentials are correct but the user does not have access to the database.
1045Access denied for user using password.This means the credentials are incorrect so you cannot connect to the MySQL server.
Check if the username and password are correct.
1049Unknown database.The database you specified in the configuration file does not exist on the server.
2002Connection timed out.This means that the database server is unreachable.
So it is either down or you are using the wrong IP address. Check with your web host to confirm the IP address.

Causes and fixes for database connection error

Let’s discuss some potential causes of a database connection error and how to fix them.

Incorrect database credentials in the wp-config.php file

If our script outputs the error code 1045, incorrect database credentials in the wp-config.php file are the culprit.
Using the correct credentials will help WordPress connect to the database again.

Get the correct database credentials

We will discuss three ways to get the correct database credentials. Pick one that’s easiest for you.

Use DirectAdmin WordPress Manager

This method is for people who have DirectAdmin as their hosting control panel. DirectAdmin has a WordPress Manager you can use to manage your WordPress installations.

Scroll to Advanced Features on the control panel homepage and click on WordPress Manager to see a list of WordPress installations.

Now, click on the Manage Database Configuration button for the website whose credentials you want to verify.

This will open a new pop-up with all the database credentials, as shown below.

Update the values in the wp-config.php file so they match the values in the pop-up.

Use Softaculous WordPress Manager in cPanel

Softaculous is a popular script library that can automatically install various web applications, including content management systems such as WordPress.

Some web hosts provide cPanel control panels with Softaculous pre-installed.Softaculous offers a WordPress Manager to easily manage your WordPress installations. Open it by clicking on WordPress Manager by Softaculous in the left sidebar in cPanel.

You should now see a list of WordPress installations.

Click the arrow on the right to see the website’s details.

Click Database Details to see the database name, database user, and the database host for the selected website.

Copy these values and update the records in your wp-config.php file.

Unlike DirectAdmin WordPress Manager, Softaculous WordPress Manager doesn’t allow users to see or change their database password.

We’ll discuss how to update the database user password at the end of the next section.

Use your web host’s control panel

You can also use built-in database management tools in a hosting control panel to verify database credentials.

We are using the cPanel control panel here, but the steps will also apply to other hosting control panels.

Confirm the database name and database host

Click phpMyAdmin under the Databases section on the cPanel dashboard homepage.

You can find the database hostname near the top on the next page. The hostname, which is localhost in this case, is written beside Server. 3306 is the default port number MySQL uses to communicate.

There is also a database list in the left sidebar on the same page.

If a database name in the sidebar matches the one in the wp-config.php file, it is your website database.

If no database name matches, you can check the value of the siteurl option in the options table of each database to see if it matches your website URL. A matching URL value in any database means it is your website’s database.

Follow the steps below to check the siteurl option value.

Click on a database name to see if it has an options table. A WordPress database will always have this table.

You can enter “options” in the text field below the database to filter tables by name.

The options table has the prefix wp_ by default. But, it can also have a different prefix depending on the value provided during website installation.

In our case, the options table is alwK_options.

Click the options table to load its data in the right panel.

The option_value for siteurl matching your website URL address means you have the correct database.

Confirm the database username

You can easily verify the database username once you know the database name.

Click on MySQL Databases under Databases on the cPanel dashboard homepage.

Scroll to Current Databases on the next page to get a list of databases and their privileged users.

Look for the database name you found in the previous section. Make sure the username listed under Privileged Users matches the database username in the wp-config.php file.

Update the database password

We mentioned earlier that DirectAdmin WordPress Manager allows users to see the database password in plain text.

You cannot see the database user password in plain text in cPanel but you can reset it. The MySQL Databases page has a Current Users section a bit further down where you will see a list of database usernames.

Find the database username from the previous section in the list. Click the corresponding Change Password button to change its password. Once you have changed the password, update it in the wp-config.php file.

Check if updating the credentials fixed the database connection error

The wp-config.php file now has the correct database credentials. Save and upload it in your website’s root directory.

Visit the website in a browser and the database connection error should be gone. If it still exists, use our script to get the database error code and figure out the problem.

Corrupt database

A WordPress website pulls data from multiple tables to generate a dynamic webpage for users. A corrupt database will prevent the website from reading this data and lead to connection errors.

A database can get corrupted for many reasons. Some of these include:

  • A poorly coded plugin or theme executed malformed queries on the database
  • Someone accidentally deleted critical database tables
  • Unexpected database server shutdowns during a write operation on the database

One sign of a corrupt database is that WordPress shows the following error message when you visit the website’s admin dashboard.

But, regular website visitors will still see “Error establishing a database connection.”

Follow these steps to fix minor database corruption automatically using the WordPress database repair tool.

Add database repair directive to wp-config.php

Open the wp-config.php file in a text editor and add the following line at the end.

define (‘WP_ALLOW_REPAIR’, true);

It tells WordPress you want to enable automatic database repair. Save the file and upload it back to the server.

Open the database repair tool

Visit http://your-website.com/wp-admin/maint/repair.php from a browser. You should see something like the image below.

There are two options available, Repair Database, and Repair and Optimize database.

  • When you click on Repair Database, WordPress tries to fix some minor problems such as incorrect data types automatically.
  • When you click on Repair and Optimize database, WordPress tries to repair as well as optimize the database. This could improve your website’s performance in certain situations.

Click Repair Database.

Once WordPress completes the database repair, visit your site’s homepage to verify the connection error no longer exists.

Please note that the automatic repair tool has limited scope and can’t fix all database errors. For instance, it can’t fix database connection errors caused by a missing core table or severe corruption.

In such cases, your best bet is to restore your WordPress database from a backup.

Remove database repair directive from wp-config.php

Did you notice accessing the database repair page required no authentication?
This is intentional because WordPress can’t authenticate users without connecting to the database.
This also means anyone can access the database repair page and access crucial information like the prefix you attach to database tables.
You can prevent bad actors from finding this information by removing the line of code we added from the wp-config.php file once the repair completes.

The line of code to remove is:

define (‘WP_ALLOW_REPAIR’, true);

Save the file and upload it back to the server.

Now visit http://your-website.com/wp-admin/maint/repair.php again to make sure the database repair page is no longer accessible.

Corrupt WordPress core files

Core WordPress files have code that connects to the database and performs read/write operations.

Websites can throw a database connection error if the files responsible for communicating with the database get corrupted.

Installing a fresh copy of WordPress core files by following the steps below can fix this problem.

Download the correct WordPress core files

You should download core files for the WordPress version running on your website to avoid compatibility issues. Ideally, it would be the latest version, but it is still best to check.
How do you find the installed WordPress version if the site isn’t working?
It’s easy.
Open an FTP client and go to your website’s root directory. Now, enter the wp-includes directory within the root directory.

WordPress stores the current version number along with other information inside the version.php file within the wp-includes directory.

Download the file and open it in a plain text editor. Search for the following line in the file:

$wp_version = ‘6.4.3’;

It mentions the version number, which is 6.4.3 in our case. Visit the WordPress.org releases page and download the WordPress version you found in your file.

Delete the wp-content folder

Extract the downloaded WordPress archive and then delete the wp-content folder inside it.

Why delete the folder, you might ask? The wp-content folder currently in your root directory has content, themes, and plugins specific to your website. You don’t want to overwrite your customizations with the files in an untouched wp-content folder from the downloaded WordPress archive.

Upload and overwrite everything else

WordPress files that handle core website functions like database connections, user management, and content management are outside the wp-content directory.

Replace all these files by uploading their fresh copies to your website root directory using an FTP client.

Tell the FTP client to overwrite existing files when it asks how to proceed if the target file already exists. For reference, the image below shows the confirmation prompt in WinSCP.

Once the overwrite completes, visit your website in a browser to confirm the database connection error no longer exists.

Unavailable MySQL server

Sometimes WordPress websites face errors establishing a database connection if the MySQL server is unavailable.

The MySQL server can become unavailable or unresponsive for many reasons like unexpected shutdowns, disk failure, or insufficient resources.

You can resolve problems caused by insufficient resources, which is the most likely cause of an unavailable MySQL server, by increasing allocated memory or reducing the number of connections.

Increase allocated memory

If our test script outputs the error code 1041, the MySQL server has run out of memory.

You should contact your hosting provider support staff and ask them to allocate more memory to the MySQL server.

Unfortunately, this could be a temporary fix.

Unless the MySQL server had very little allocated memory, running out of memory is often a symptom of inefficient code.

Resource-intensive database queries and memory leaks in the code can cause the server to run out of memory.

Consider hiring a developer to figure out which code on your site is the culprit.

Reduce the number of connections

The error code 1040 implies too many database connections.

Your WordPress website creates a database connection every time someone visits a page. WordPress automatically closes this connection after generating the requested webpage.

However, long-running code in a theme or plugin can keep a connection open for a long time. A few users will exhaust all available connections in such cases.

Even without long-running code, a lot of visitors accessing your website at once can also create too many database connections.

There are a few things that you can do to resolve this error:

  1. Optimize the code so it executes quickly and frees up the connection.
  2. Reduce the number of processes and applications simultaneously using the database server.
  3. Distribute the connection load to several servers.

Lack of user privileges

Our script will give the error code 1041 if the MySQL user lacks the required database privileges.

You can fix this error by creating a dedicated user with read and write permissions for the WordPress database.

Create a new user with desired permissions

Click on MySQL Databases under the Databases section in the cPanel dashboard. Next, scroll down to the Add New User section on the next page.

Enter a new username and password, and click the Create User button. Now, scroll down to the Add User to Database section.

Select the newly created database user and the website database name from the selection dropdowns. Click on the Add button to go to the next page to assign privileges to this user.

Select four privileges: SELECT, INSERT, UPDATE, and DELETE. These privileges are enough to keep your website running normally. Granting the minimum possible privileges will help secure your WordPress database.

Some WordPress themes, plugins, and WordPress updates might occasionally need additional database privileges to complete tasks like creating new tables. You can temporarily grant new privileges in such cases.

Now, click on the Make Changes button to confirm your selection.

Connect to the database server using the new user credentials. You should no longer see the 1041 error code.

Conclusion

In this guide, we discussed how to determine why a website can’t establish a database connection.

Then, we explained how to fix common issues like incorrect WordPress database credentials, corrupt database tables, corrupt WordPress files, lack of user privileges, and lack of resources.

Sometimes, a database connection error can have multiple causes. It is a good idea to use our script and confirm you have fixed all the issues.

We hope following the steps in this guide resolves your WordPress database connection errors.

Frequently Asked Questions

Why won’t my WordPress connect to the database?

There are many reasons a WordPress site won’t connect to the database. It could be because of incorrect login credentials, lack of user privilege, corrupt files, corrupt database, and unavailable MySQL server among other things.

Why does WordPress throw an error establishing a database connection randomly?

If a WordPress website randomly throws an error establishing a database connection, the likely culprits are lack of memory, or too many connections. Such errors usually go away automatically once the traffic reduces and the server is no longer overloaded. You might want to allocate more resources and optimize your scripts if the error occurs frequently.

Posted inWordPress Management
Nitish Kumar
Nitish Kumar

Nitish is a freelance web developer and technical writer with experience in various web development technologies, including WordPress. He specializes in developing eCommerce websites and likes to spend his free time working on personal projects or going out with friends.


Leave a Reply

Your email address will not be published. Required fields are marked *

Stay in the loop

Subscribe to the Melapress newsletter and receive curated WordPress management and security tips and content.

Newsletter icon

It’s free and you can unsubscribe whenever you want. Check our blog for a taste.

Envelope icon
newsletter-pop-up