What Is ‘Error Establishing a Database Connection’ & How To Fix It in WordPress
2023-9-27 04:10:49 Author: blog.sucuri.net(查看原文) 阅读量:19 收藏

Experiencing the ‘Error Establishing a Database Connection‘ on your WordPress website? This common error indicates that your site is unable to connect to its database, rendering it inaccessible to users — and potentially impacting your visitors, user experience, and sales.

In this blog post, we’ll explain what the database connection error means, common reasons for the issue, and how to troubleshoot and fix the problem to get your website back online.

Contents:

What is ‘Error Establishing a Database Connection’?

The “Error Establishing a Database Connection” is a WordPress error message that appears when the CMS cannot connect to its MySQL database.

Example notification of Error establishing a database connection WordPress message We can't contact the database server at localhost

This error occurs because WordPress needs to fetch site information from the database to display it on visitors’ browsers. Without a successful database connection, no data can be retrieved, resulting in the error message on a blank page.

The most common reason for this error are incorrect credentials in the wp-config.php file, however it can also appear if database files have been corrupted or your server is down.

Understanding how WordPress connects to the database

WordPress consists of two key parts: your website files and a database.

Your website files consist of media content (such as images) along with theme, plugin, and core files such as index.php and wp-login.php, while your database stores the meta, page, and post data, custom settings, login details, and content.

When a visitor navigates to your website, the files communicate with the database via PHP and MySQL functions to extract the data and visualize it on a web page.
How a WordPress database connects with MySQL server and PHP functions to serve website contentIf your website fails to connect to the database, it can’t retrieve the data required to display the page and triggers the “Error Establishing a Database Connection” message. This also prevents access to the WordPress dashboard and causes the website to generate a 500 HTTP status code, indicating an internal server error.

While visitors may not immediately see database connection errors on your site due to caching, it’s important to address the cause and fix the issue as soon as possible to keep your website online and accessible.

How to fix a database connection error in WordPress

Before you start troubleshooting, you’ll want to check for a recent website backup. Restoring your website from a most recent backup and rebooting your web server may be the path of least resistance and a good starting point.

If you don’t have a backup to restore from, then you’ll want to start now. Please make a backup of your entire WordPress site and database (if you can still connect to it using other tools) before proceeding with these next steps. This will help you easily restore your site in the event of an unexpected issue.

There are many tools and services you can use to backup your website. If you like the command line, you can use WP-CLI to backup your WordPress website and database for free.

Once you’ve got a backup of your website files and database, you can follow these steps to fix the database connection error in WordPress.

  1. Check your database name and login credentials in wp-config.php
  2. Make sure your database is up and running
  3. Fix any corrupted WordPress files
  4. Repair your corrupted database
  5. Check with your host for issues with your database server
  6. Scan your server and database for malware

Step 1: Check your database name and login credentials in wp-config.php

Quite often, the “Error establishing a database connection” message occurs due to incorrect database login credentials. This is especially common right after people migrate their WordPress site to a new hosting provider.

The connection details for your WordPress site are stored in the wp-config.php file, which is most often found at the root of your WordPress site.

Example contents of a WordPress configuration wp-config.php file.
Example contents of a wp-config.php file.

The wp-config.php file contains four critical pieces of information required for a successful database connection:

  • Database Name – DB_NAME
  • MySQL database username – DB_USER
  • MySQL database password – DB_PASSWORD
  • MySQL hostname (server) – DB_HOST

So, let’s go ahead and check your credentials to make sure they match.

To access your wp-config.php file, connect to your site via an sFTP client and navigate to the root of your site. Alternatively if you are using cPanel you can click on “File Manager“, then browse to the root of your site and right-click to edit the file.

Check the database name:

Once you’ve opened up wp-config.php, you’ll see your database name. Check these values against those on your server.

For cPanel users:

  1. Log in to phpMyAdmin under the Database section. You should see your database name on the left.
  2. Compare this name against the DB_NAME value in your wp-config.php file.

If your database names match, then this isn’t the problem. But if they don’t match, you’ll need to update the DB_NAME value in your wp-config.php file to match the database name found in phpMyAdmin.

Check the database username and password:

If your database name is correct but you’re still getting a connection error, you’ll want to check your username and password next.

You can try creating a new PHP file in the root directory of your WordPress site that attempts to connect to the database using the credentials in your wp-config.php file.

<?php

$test = mysqli_connect('localhost', 'db_user', 'db_password');
if (!$test) {
die('MySQL Error: ' . mysqli_error());
}
echo 'Congrats - your DB connection is working! :)';
mysqli_close($testConnection);

If this connection fails, we’ve now verified that your username and/or password are incorrect. To fix this, you will need to change your password and update it in the wp-config.php file to match what is specified on your MySQL server.

For cPanel users:

  1. Click on MySQL Database under the Database section.
  2. Locate your MySQL user.
  3. Select the Change Password link.
  4. Update your user with a strong and unique password.
  5. Click Change Password to proceed.Change MySQL password to fix database connection error
  6. Update the DB_USER and DB_PASSWORD values in your wp-config.php file to match your MySQL credentials.

If you’re on a shared hosting environment, you might only have one database username and you might not be able to change it. In this case, contact your hosting provider for assistance.

Check the database hostname (server):

If you’re still receiving the error after checking your database name, username, and password, then your hostname (DB_HOST) could be the issue. 90% of the time this should be defined as localhost, but in rarer cases hosts will use a local IP. So, you may need to check with your hosting provider’s documentation if you’re not sure what this should be.

If you’ve followed all these steps and are still receiving the “Error establishing a database connection” message, move to the next step.

Step 2: Make sure your WordPress database is up and running

In some cases, heavy server traffic can overload your host server; this is a more common issue for shared hosting environments.

To begin, try connecting to your database through phpMyAdmin from your cPanel environment, or use Adminer to ensure your SQL server is actually running. If you have other sites in the same environment, try checking those sites as well to check if your SQL server is down or not.

If the connection works fine for other environments, move to the next step. But if the database is down, you’ll want to get in touch with your hosting provider and ask about your MySQL server.

Step 3: Fix corrupted WordPress core files

Corrupt core WordPress files could be yet another reason you’re seeing the “Error establishing a database connection” message. Corrupted files could happen due to a failed update, a problem with transferring files via FTP, or even be an indicator of compromise.

To fix corrupted WordPress core files:

  1. Download a fresh copy of WordPress from the official website.
  2. Unzip the downloaded file on your local computer and open it.
  3. Delete the wp-content folder to avoid overwriting your existing themes and plugins.
  4. Delete the wp-config-sample.php file. It’s just a sample and you don’t need it.
  5. Connect to your website using your favorite sFTP client (like FileZilla).
  6. Navigate to the root directory of your WordPress installation. This is usually named ‘public_html‘ or ‘www’.
  7. Upload the remaining files from your local WordPress folder to your website to overwrite existing files and replace everything except for your ‘wp-content‘ folder and ‘wp-config.php‘ file with fresh copies.
  8. Clear your browser cache to ensure you’re not loading any old files from your cache.
  9. Visit your website to see if the error has been resolved.

If you’re still seeing the connection error after replacing the WordPress files, there might be an issue with your database or server. Proceed to the next step.

Step 4: Repair your corrupted database

In some cases, the “Error establishing a database connection” message can occur because your database has become corrupted.

If the database is corrupted but MySQL is still working, you can try restoring your database from a backup. If you don’t have a backup, you can take a stab restoring corrupted database tables.

Corrupted database tables can occur if tables have been added or removed by new plugins and themes, or due to more unexpected issues like server crashes or website malware. While it isn’t directly related to this particular database connection error, it may help avoid other problems and preserve some of your website data.

WordPress includes a built-in feature to repair your database tables. To enable this feature, you need to add a line of code to your wp-config.php file:

define('WP_ALLOW_REPAIR', true);

Once you’ve added that line, save the changes to wp-config and navigate to the following URL in your web browser:

http://www.examplewebsite.com/wp-admin/maint/repair.php

Replace “www.examplewebsite.com” with your actual website URL. You should now see a page with two options: “Repair Database” and “Repair and Optimize Database“.

Since you’re troubleshooting an outage and you have a backup, it’s recommended to use the “Repair Database” option — it’s quicker.

Click on “Repair Database” to initiate the repair process. At this point, WordPress will attempt to fix any issues with your database. Once the repair is done, you should see a success message.

Important: Remember to remove the line of code you added to your wp-config.php file after the repair process is done. If you leave this line of code in wp-config, the repair page remains accessible to anyone — this is a potential security risk.

Repairing corrupted database with phpMyAdmin

If you’re a phpMyAdmin user, this tool offers the option to quickly repair MySQL database tables.

To repair a corrupted database with phpMyAdmin:

  1. Connect to phpMyAdmin.
  2. Select the affected database.
  3. Click on the Check all option.
  4. Click on the With Selection dropdown and choose Repair Table.

If you’ve tried repairing the database and are still seeing the error, take a look at the next troubleshooting step.

Step 5: Check with your host for issues with your database server

If none of the above steps resolves the issue, it’s possible that the problem lies with your database server. This could be due to the server being down or overloaded, or there may be a configuration issue.

You may need to contact your hosting provider for assistance. They should be able to check the status of the server and fix any server-related problems that might be causing the error.

Too many concurrent connections to your database can also result in database connection errors, which happens when your server reaches its maximum capacity of handling connections at once. This is because many hosting providers limit the number of simultaneous connections their servers can handle.

Shared hosting environments can face this issue, as multiple websites share the same resources, making it easier for the server to reach its limit. In such cases, consider upgrading to a higher-performance hosting plan or a managed WordPress hosting provider that can handle a larger amount of traffic and minimize server-related issues.

Remember to be patient when dealing with server-related issues. It might take a bit of time for your hosting provider to diagnose and fix the problem.

Step 6: Scan your server and database for malware

While much rarer, website malware is another potential cause of the “Error establishing a database connection” message. If hackers manage to inject malicious code into your site, it could corrupt your files or database.

There are a couple of ways you can check for indicators of compromise and clean up malware on your WordPress site:

  1. Install a security plugin: WordPress security plugins like Sucuri or Wordfence can make it easy to scan your site for malware. These plugins will check your WordPress files and database for any signs of malicious code. If they find anything suspicious, they’ll alert you and provide you with steps to clean up the infection.
  2. Manually inspect your database tables and website files: If you suspect a specific file might be infected, you can download it via FTP and inspect it manually. Look for any code that appears out of place or suspicious. Be cautious with this method, as editing WordPress files without understanding the code can break your site.
  3. Update your software: Make sure all your WordPress themes, plugins, and core are updated to the latest versions. Updates often include security patches for known vulnerabilities that can help prevent malware infections.
  4. Seek help: If you’re not comfortable dealing with malware or if the infection is severe, consider hiring an expert. Sucuri offers professional malware removal services and quick turn-around times to help you clean up an infection in your server or database.
  5. Strengthen your website security: Beyond dealing with the immediate issue, consider steps to improve your website’s security overall. This might include using strong passwords, limiting login attempts, implementing a website firewall, and regularly backing up your site.

Remember, dealing with malware can be complex. It’s crucial that you ensure you’ve completely cleaned your site to prevent reinfections. Always keep a backup of your site before making any changes. If in doubt, consult with a professional.

What causes the ‘Error Establishing a Database Connection’ issue?

Let’s take a look at some of the most common causes for database connection errors in WordPress.

Incorrect database login credentials

One of the most common causes of the “Error Establishing a Database Connection” is incorrect database login credentials.

WordPress uses separate login credentials to connect to its MySQL database. If the user or password are changed for any reason — or you migrate your blog to another host and the WordPress files are not updated with the new details — the connection to the database will fail. This disconnect between stored credentials and actual database login details can disrupt the operation of your website, resulting in a connection error.

Corrupted database

A corrupted database is another common cause of this error. A WordPress database can become corrupted due to a variety of factors including abnormal process termination, sloppy server administration — or, much more rarer MySQL bugs, software issues, and server-level malware; for example: ransomware that encrypts your database files.

When critical information within the database is missing or corrupted, the database can’t function properly which disrupts the website’s ability to connect to the database, ultimately leading to a DB connection error.

Issues with the database server

Sometimes the issue lies not with the website itself, but with your database server — especially if it’s hosted on a shared server.

The most obvious circumstance could be that your database server is currently under maintenance – for example, updating important software or moving to another server. Or it could have simply run out of space and resources. But in other cases, sudden surges in traffic or too many concurrent connections can overload the server and cause it to become unresponsive. This issue can be especially common in shared hosting environments where resources are used by multiple websites simultaneously.

Corrupted WordPress core files

Your core WordPress files dictate the functionality and operation of your website. If these files become corrupted due to malicious plugins, incorrect modifications, website malware, or issues during file transfers, they can interfere with your website’s ability to connect to the database.

How can website malware cause errors connecting to a database?

One common way malware can cause database connection errors is by altering the website’s configuration files.

For example, wp-config.php contains crucial information about the website’s database including its name, the username, password, and host. If malware manages to modify or corrupt your WP-Config file, it can lead to connectivity issues and errors.

On average, our malware remediation team removes malicious code from over 1,000 wp-config.php files a month. A buggy malware injection or sloppy malware removal rules can easily corrupt this file, making the WordPress database unreachable.

In other cases, malware might not alter the configuration files directly, but instead overload the database server. Malicious scripts can create an unnaturally high number of requests to the database, causing the server to reach its maximum capacity and refuse any additional connections. This can manifest as intermittent database connection errors, especially during peak traffic times.

Malware can also lead to other types of database connection errors. For instance, some types of malware, known as ransomware, can lock you out of your database entirely. The malware encrypts your database, making it inaccessible. It then demands a ransom to decrypt it. In such cases, you might see a database connection error because your website can no longer access the data it needs.

Additionally, malware can also cause connection errors by attacking the server’s file system. For example, it might include code that deletes or moves crucial files. And if your website or database files are deleted or moved, your website may not be able to connect to your DB.

Scanning your website for indicators of compromise, using a website firewall, and keeping all software patched with the latest updates are some of the best defenses against website malware.

If you suspect your website or database has been infected, you can check out our free guide on how to clean up a hacked WordPress website. And if you need a hand, our trained security analysts are available 24/7/365 to help clean up a website malware infection!


文章来源: https://blog.sucuri.net/2023/09/what-is-error-establishing-a-database-connection-how-to-fix-it-in-wordpress.html
如有侵权请联系:admin#unsafe.sh