How to Fix the Error Establishing a Database Connection in WordPress

How to Fix “Error Establishing a Database Connection” in WordPress

Last updated on

by


The “error establishing a database connection” is one of the most frequent issues WordPress users face. It’s often linked to the infamous “White Screen of Death in WordPress” (WSoD).

This error appears when your website cannot communicate with the WordPress database, which effectively makes your entire site inaccessible. The fact that there are a number of factors that can impact this connection, troubleshooting this issue can be challenging, especially for beginners.

But don’t worry, we’ve got you covered!

In this guide, we will show you six simple yet effective solutions to fix the database connection error on your WordPress website.

Ready? Let’s get started!

What is Error Establishing a Database Connection?

The database connection error occurs when a website cannot connect to the WordPress database, stopping the page from loading. This often occurs as a result of incorrect login credentials or database corruption.

Here’s how it works: all essential data on your WordPress site—like posts, pages, meta info, plugin settings, and login details—is stored in your MySQL database. The only content not stored in the database is media (like images) and core files (such as index.php and wp-login.php).

When someone visits your site, PHP processes the page’s code, retrieves the information from the database, and displays it in the visitor’s browser. If this process fails, you’ll see the “error establishing a database connection” message on a blank screen, as no data is available to load the page. This error disrupts the frontend and also locks you out of the WordPress dashboard.

NOTE: If your website cache is active, the message may not show up immediately, making the error less noticeable at first. However, an inaccessible admin dashboard often signals a database connection issue in WordPress.

Reasons Behind Error Establishing a Database Connection in WordPress

You might be wondering why this error occurs. Here are a few common reasons, which we’ll cover in more detail so you can fix them efficiently include:

  • WP-config file has incorrect database login credentials: WordPress relies on login details provided by your hosting provider to access the database. If the MySQL database username or password changes, any old credentials in the configuration files will cause issues.
  • Corrupted database: Plugins or incompatible themes can corrupt database tables or their contents, leading to errors.
  • Database server error: Issues within your web host’s infrastructure, like traffic spikes or permission issues, can make the database server unresponsive.
  • Corrupted WordPress core files: Core WordPress files define how your site operates. Corrupt code in plugins or themes can damage these files, resulting in database connection failures.

Often, a pop-up message will hint at the source of the problem. For example, if you encounter the following error message in your WordPress admin dashboard, it means the incorrect database login credentials are often the underlying cause.

6 Effective Methods to Fix the “Error Establishing a Database Connection” in WordPress

Before you get into troubleshooting, make sure you back up your WordPress site. Fixing this error often requires changes to your database, so having a backup will help you avoid further issues. So, regardless of your tech expertise, always back up your site before making any fixes.

You can use a trusted WordPress backup plugin like VaultPress or WP Time Capsule to safely back up both your files and database.

Now, let’s explore how you can resolve this error effectively.

#1: Check Your WordPress Database Login Credentials

The most common reason for the WordPress database connection error is incorrect database login details, especially after a recent hosting migration. These credentials are stored in your wp-config.php file, located in the root directory of your WordPress site.

This file contains four critical details necessary for your site to connect to the database:

  1. Database Name
// The name of the database for WordPress

define('DB_NAME', 'xxxxxx');
  1. MySQL Database Username
// MySQL database username

define('DB_USER', 'xxxxxx');
  1. MySQL Database Password
// MySQL database password

define('DB_PASSWORD', 'xxxxxxxxx');
  1. MySQL Hostname (Server)
// MySQL hostname

define('DB_HOST', 'localhost');

To access the wp-config.php file, connect to your site an FTP client like FileZilla to view your site files.

As an example, here is what the wp-config.php file looks like:

Next, verify that the database name, username, password, and host values match those on your hosting account.

For instance, if you’re using Bluehost, you can find these details under the “Website” tab by going to “Advanced” and selecting “Database.” Here, click the ‘Manage’ button.

You will be redirected to MySQL Databases under cPanel. Then, in the “Current Database” section, check your database name and username, then copy these to update in the wp-config.php file if needed.

If necessary, change the database password in the “Current Users” section by clicking “Change Password.”

Once you’ve updated the wp-config.php file with any corrected details, refresh your site to see if the error is resolved. If the issue persists, another underlying problem may be the cause.

#2: Repair Your Corrupt WordPress Database

If you see an error in your WordPress admin dashboard such as “One or more database tables are unavailable” or “The database may need to be repaired,” this typically means your database is corrupt and needs repair.

To repair it, add this line to your wp-config.php file right before the “That’s all, stop editing! Happy blogging” line:

define('WP_ALLOW_REPAIR', true);

After saving this change, go to http://www.yoursite.com/wp-admin/maint/repair.php (replace “yoursite.com” with your own domain). On this page, click “Repair Database” to start the process.

NOTE: You don’t need to be logged in to access this repair page. After the repair is complete, make sure to remove this line from your wp-config.php file to prevent unauthorized access to the repair page.

If you prefer not to edit files, you can repair the database directly through cPanel. Go to your hosting account’s “Websites” page, switch to the “Advanced” tab, and click “Manage” under the Database section.

In the “Modify Databases” section, select your database from the “Repair Database” dropdown, and click “Repair Database” to start the repair.

Your database will now be automatically repaired by your hosting panel. Upon completion, a success message will appear.

Alternatively, if you have WP-CLI access, you can repair the database with the following command:

wp db repair

For more information, see the WordPress developer resources.

Once the repair is complete, refresh your site to see if the database connection issue has been resolved.

#3: Fix all the Corrupted Files on Your Site

Corrupted files, often caused by faulty themes or plugins, can also lead to the WordPress Database Connection Error issue. If you recently installed or updated a theme or plugin, it may be the root of the problem.

Start by deactivating the most recent plugin or theme, as it’s likely to be causing the issue. If you have multiple plugins, try deactivating all of them and then re-enabling each one individually.

To deactivate all plugins at once, go to your WordPress dashboard, click on Plugins in the sidebar, select all plugins by checking the box at the top, choose Deactivate from the Bulk actions dropdown, and then click Apply.

For themes, go to Appearance > Themes in the dashboard to switch between them one by one. If you can’t access your dashboard due to the database error, deactivate all plugins by renaming the plugins folder in File Manager or an FTP client.

Once renamed, try accessing your admin area again. If successful, rename the plugins folder back to its original name. You’ll now see all plugins deactivated in the dashboard; reactivate each one individually to identify the problematic plugin. Delete any faulty plugins by clicking Delete below their names.

If none of these steps resolve the issue, your WordPress core files may be corrupt. To fix this, replace your core files with fresh ones from a new WordPress installation. Download the WordPress package, extract it, and remove the wp-content folder and wp-config-sample.php file. Then, upload the remaining files to your website’s root directory via File Manager or FTP.

IMPORTANT: Avoid reinstalling WordPress from scratch, as this can erase all your site’s data. Instead, only replace the core files to avoid data loss.

#4: Update Your WordPress site URL

Updating your WordPress site URL can sometimes fix the database connection error. To do this, use the phpMyAdmin tool.

Start by logging into phpMyAdmin and selecting the database with the issue. Go to the SQL tab.

In the left-hand column, locate the table name, typically wp_options by default. Enter the following MySQL query, replacing YOUR_URL with your actual site’s URL and wp_options with your table name if it’s different:

UPDATE wp_options SET option_value='YOUR_URL' WHERE option_name='siteurl'

Run the query and then try accessing your site again to see if this resolves the error.

#5: Check Whether the Database Server is Down

If everything appears correct but WordPress still fails to connect to the database, your database server (MySQL server) might be down. This situation can arise from heavy server traffic, particularly if you’re using shared hosting, which might not handle the load effectively. As a result, your site may slow down or display errors for some users.

In this case, contact your hosting provider via phone or live chat to inquire about the status of your MySQL server. If you have other websites on the same server, check their functionality to determine if the SQL server is indeed down.

If you don’t manage additional sites, access your hosting dashboard and navigate to the Advanced tab. Click the Manage button next to the phpMyAdmin section to open it in a new window.

From there, select the Database option at the top and then click on your database name to access its settings. If this process works, verify that your database user has adequate permissions.

To check permissions, create a file named testconnection.php and insert the following code:

<?php

$link = mysqli_connect('localhost', 'username', 'password');

if (!$link) {

    die('Could not connect: ' . mysqli_error());

}

echo 'Connected successfully';

mysqli_close($link);

?>

Make sure to replace username and password with your actual credentials.

Upload this file to your website and access it via a web browser. If the script connects successfully, your user has the necessary permissions, indicating that something else is causing the error.

Now, you should review the wp-config.php file and double-check that all details are correct and free of typos.

#6: Restore Your Latest Site Backup

Finally, restoring a backup can be a viable solution if other methods fail. This approach can often resolve the issue more quickly, especially if you’re not concerned about losing any data since your last backup. Many hosting providers offer their own backup restoration processes, so check with them to understand the specific steps.

To restore your backup, log into your web hosting account. The process may vary depending on your host, so consult their documentation or contact their support team for precise instructions on restoring your WordPress backup.

Remember that you might need to restore both your database and your files to fully resolve the issue.

How to Prevent the Error Establishing a Database Connection in WordPress

Database issues can negatively impact your website’s traffic and search engine optimization. Once you resolve the error, implement the following best practices to prevent its recurrence:

  • Optimize Your WordPress Database: Use a plugin like WP-Optimize to clean up your database. Excessive data can slow down your website’s back end, potentially leading to downtime and connectivity errors.
  • Use a Reliable Web Host: Choose a dependable hosting provider for your WordPress site. A good host ensures high uptime for your database and offers reliable support to help you resolve any issues that may arise.
  • Enable Automatic Backups: Regularly backup your WordPress site and its database. This ensures you have a restore point available if the issue arises again, simplifying troubleshooting and safeguarding against data loss.
  • Stay Up to Date: Follow the latest news on WordPress releases. Staying informed about updates can help you identify potential issues early and take preventive measures.
  • Install Trusted Themes and Plugins: Only download themes and plugins from reputable sources, such as the official WordPress library. Software from unknown sources may contain malware or untested code, which can conflict with WordPress functionality.
  • Stay Up-to-Date: Follow the latest news on WordPress releases, such as through Hostinger’s blog. Staying informed about updates can help you identify potential issues early and take preventive measures.
  • Regular Monitoring: Conduct routine checks of your WordPress site and database to quickly detect and address issues before they escalate.

Final Thoughts

The “Error Establishing a Database Connection” issue occurs when your WordPress site can’t retrieve the requested data from the database. Common causes include mismatched credentials, corrupted files, or server downtime.

Once you’ve pinpointed the problem, you can take steps to resolve it. Here are six effective methods to fix the database connection error in WordPress:

  1. Check Your WordPress Database Login Credentials
  2. Repair Your Corrupt WordPress Database
  3. Fix All the Corrupted Files on Your Site
  4. Update Your WordPress Site URL
  5. Check Whether the Database Server is Down
  6. Restore Your Latest Site Backup

If these methods do not resolve the issue, the problem may originate from your server. In such cases, contact your web hosting provider for assistance.

We’d love to hear about your experience! Please leave a comment below letting us know which method successfully resolved the database connection error for you.