Solving the Error Establishing a Database Connection in WordPress

Seeing the words “Error Establishing a Database Connection” can induce panic in any WordPress site owner. This error means your website is completely down because PHP cannot connect to your MySQL database to retrieve the content.

Let’s explore the primary causes and how to fix this critical issue.

What Causes a Database Connection Error?

  • Incorrect database credentials in your wp-config.php file.
  • Corrupted database tables.
  • An unresponsive database server.

How to Fix It

1. Check Your Database Credentials

The most common reason for this error is incorrect database login details. This often happens after migrating a site to a new host.

The Fix:
Open your wp-config.php file and verify the following lines match the credentials provided by your web host’s control panel (cPanel, Plesk, etc.):

// ** 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' );

Note: DB_HOST is usually localhost, but some managed hosts use a specific IP address or URL.

2. Repair a Corrupted Database

Sometimes, the database connection is fine, but the database itself has become corrupted (e.g., after an interrupted update or plugin install).

The Fix:
WordPress has a built-in repair tool. To enable it, add this single line of code to your wp-config.php file:

define( 'WP_ALLOW_REPAIR', true );

Next, navigate to: http://yourwebsite.com/wp-admin/maint/repair.php.
Click the Repair Database button. Once finished, make sure to remove the WP_ALLOW_REPAIR line from your wp-config.php file for security reasons.

3. Check with Your Web Host

If your credentials are correct and repairing the database didn’t help, your database server might be down or overloaded.

Shared hosting environments often limit the number of concurrent connections to the database. If you receive a surge of traffic, your database may temporarily shut down. In this scenario, you’ll need to contact your hosting provider’s support team to check the MySQL server status.

By following these debugging steps, you can restore your database connection and get your WordPress site functioning normally again.