
How to fix the "Error establishing a database connection" in WordPress?
The "Error establishing a database connection" message means WordPress tried to talk to its MySQL or MariaDB database and failed. In most cases, the fix is one of four things: correcting the database credentials in wp-config.php, restarting or waiting out an overloaded database server, repairing corrupted database tables, or restoring a missing or damaged database. You can usually find and fix the cause in under 30 minutes if you work through the checks in the right order.
This error is alarming because it takes your entire site offline, front end and dashboard alike. The good news is that your content is almost never gone. This guide explains why the error happens, how to diagnose the exact cause, and the step-by-step fixes for each scenario, including a few code snippets you can copy and paste.
What Does "Error Establishing a Database Connection" Mean?
WordPress stores almost everything in a database: posts, pages, users, settings, plugin options, and comments. Every time someone visits your site, PHP runs WordPress, and WordPress opens a connection to the database to fetch that content.
To make that connection, WordPress reads four values from your wp-config.php file:
- DB_NAME: The name of the database.
- DB_USER: The database username.
- DB_PASSWORD: The password for that user.
- DB_HOST: The server where the database lives, often
localhost.
If any of those values are wrong, if the database server is down or refusing connections, or if the database itself is damaged, WordPress can't load anything. Instead of showing a broken page, it displays the database connection error.
The Front End vs. the Dashboard
Pay attention to where you see the error. If both your site and /wp-admin/ show the exact same "Error establishing a database connection" message, the problem is likely credentials or the server. If the front end shows the error but /wp-admin/ shows a different message, such as "One or more database tables are unavailable. The database may need to be repaired," you are probably dealing with corrupted tables. That small difference saves you a lot of guessing.
Common Causes of the Database Connection Error
Before you start changing files, it helps to know the usual suspects:
- Incorrect database credentials: The most common cause, especially right after a migration, a hosting change, or a password reset in your hosting panel.
- Database server is down or overloaded: Shared hosting servers can hit connection limits during traffic spikes, or the MySQL service may have crashed.
- Corrupted database tables: A failed plugin update, a server crash, or a disk issue can corrupt tables like
wp_options. - Corrupted WordPress core files: Less common, but damaged core files can interfere with the connection process.
- Database user permissions changed: The user exists, but no longer has privileges on the database.
- Hosting account issues: Suspended accounts, exceeded disk quotas, or expired plans can all take the database offline.
- Hacked or modified wp-config.php: Malware sometimes rewrites configuration files.
Before You Start: Back Up What You Can
Even though this error means WordPress can't reach the database, you can often still access your files via FTP, SFTP, or your host's file manager, and your database through phpMyAdmin. Before editing anything, download a copy of wp-config.php and, if phpMyAdmin works, export the database. If something goes wrong during the fix, you'll be able to put things back exactly as they were.
If your host offers automatic daily backups, note the time of the most recent good backup. It's your safety net if the database turns out to be seriously damaged.
Step 1: Check Whether Your Host Is Having Problems
Start with the easiest check. If your host is having an outage, nothing you change on your end will help.
- Check your host's status page: Most hosts publish a status page or post incident updates on social media.
- Look at other sites on the same account: If every site on the server shows the same error, the database server is likely the problem.
- Contact support: A quick chat with support can confirm whether the MySQL service is running and whether your account has hit any limits.
If you're on a VPS or a server you manage yourself, check whether the database service is running:
sudo systemctl status mysql
# or, on MariaDB-based systems
sudo systemctl status mariadb
If it's stopped or failed, restart it:
sudo systemctl restart mysql
Then look at the logs to understand why it stopped. A MySQL server that keeps crashing is often running out of memory:
sudo journalctl -u mysql --since "1 hour ago"
sudo tail -n 100 /var/log/mysql/error.log
Step 2: Verify Your Database Credentials in wp-config.php
If the server is fine, the next suspect is the credentials. Open wp-config.php, located in the root folder of your WordPress installation (the same folder that contains wp-admin and wp-content). Look for these lines:
define( 'DB_NAME', 'your_database_name' );
define( 'DB_USER', 'your_database_user' );
define( 'DB_PASSWORD', 'your_database_password' );
define( 'DB_HOST', 'localhost' );
Now compare each value with what your hosting account actually has.
How to Find the Correct Values
- Log in to your hosting control panel: In cPanel, open Databases > MySQL Databases. Other panels have a similar "Databases" section.
- Confirm the database name: Check that the database listed in
DB_NAMEexists. On shared hosting, names often include an account prefix, likeaccount_wp123. - Confirm the user is attached to the database: Under "Current Databases," check that your
DB_USERis listed as a privileged user for that database. - Reset the password if unsure: You can't view an existing MySQL password, but you can set a new one for the user and paste that same password into
DB_PASSWORD. - Confirm DB_HOST: Many hosts use
localhost, but some use a dedicated hostname, an IP address, or a hostname with a port, likemysql.example.com:3306. Check your host's documentation.
Watch out for small details. An extra space inside the quotes, a curly quote pasted from a word processor, or a missing prefix will all break the connection.
Test the Credentials Directly
To confirm whether the credentials work independently of WordPress, create a temporary file called db-test.php in your WordPress root folder:
<?php
// Temporary database connection test. Delete this file after use.
$link = mysqli_connect( 'localhost', 'your_database_user', 'your_database_password', 'your_database_name' );
if ( ! $link ) {
echo 'Connection failed: ' . htmlspecialchars( mysqli_connect_error() );
exit;
}
echo 'Connected successfully.';
mysqli_close( $link );
Visit https://yourdomain.com/db-test.php in your browser. If you see "Connected successfully," the credentials are correct and the issue lies elsewhere. If you see an "Access denied" message, the username or password is wrong. If you see "Unknown database," the database name is wrong. If the connection times out or is refused, DB_HOST is wrong or the server is down.
Delete db-test.php immediately after testing. Leaving a file with your database credentials on a public server is a serious security risk.
Test From the Command Line
If you have SSH access, you can test the same thing with the MySQL client:
mysql -h localhost -u your_database_user -p your_database_name
Enter the password when prompted. If you land at a mysql> prompt, the credentials work. Type exit to leave.
Step 3: Repair Corrupted Database Tables
If your credentials are correct but the dashboard says the database needs repair, WordPress has a built-in repair tool.
- Enable the repair mode: Open
wp-config.phpand add the following line above the/* That's all, stop editing! Happy publishing. */comment:
define( 'WP_ALLOW_REPAIR', true );
-
Run the repair tool: Visit
https://yourdomain.com/wp-admin/maint/repair.php. You'll see two buttons: "Repair Database" and "Repair and Optimize Database." Either works; the second takes longer. -
Remove the line afterward: The repair page doesn't require you to be logged in, so anyone could access it while this constant is set. Delete the line from
wp-config.phpas soon as you're done.
Repair With phpMyAdmin
You can also repair tables through phpMyAdmin:
- Open phpMyAdmin: Usually found under Databases > phpMyAdmin in your hosting panel.
- Select your WordPress database: Click its name in the left sidebar.
- Select all tables: Use the "Check all" checkbox below the table list.
- Repair: From the "With selected" dropdown, choose "Repair table."
Repair With WP-CLI
If you're comfortable with the command line, WP-CLI makes this quick. Run these from your WordPress root folder:
wp db check
wp db repair
Note that wp db repair works for MyISAM tables. Most modern WordPress sites use InnoDB, which handles crash recovery on its own. If InnoDB tables are badly damaged, restoring from a backup is usually the safest route.
Step 4: Check the Site URL in the Database
After a migration, credentials may be correct, but the site URL stored in the database points somewhere else. This usually causes redirects rather than the connection error, but it's worth checking while you're in phpMyAdmin. Run this query, replacing wp_ with your table prefix if it's different:
SELECT option_name, option_value
FROM wp_options
WHERE option_name IN ('siteurl', 'home');
If the URLs are wrong, you can update them:
UPDATE wp_options
SET option_value = 'https://yourdomain.com'
WHERE option_name IN ('siteurl', 'home');
Also confirm that the $table_prefix value in wp-config.php matches the actual prefix of your tables. If your tables are named wpxy_posts but the config says wp_, WordPress will think the tables are missing.
Step 5: Check Database User Privileges
Sometimes the user exists and the password is right, but the user has lost its privileges. In cPanel, go to Databases > MySQL Databases, scroll to "Add User to Database," select your user and database, and grant "All Privileges."
On a self-managed server, you can do this in the MySQL shell:
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_database_user'@'localhost';
FLUSH PRIVILEGES;
Step 6: Replace Corrupted WordPress Core Files
If everything above checks out, a corrupted core file may be the culprit. You can replace the core files without touching your content:
- Download a fresh copy: Get the same version of WordPress you're running from WordPress.org.
- Extract it on your computer: Delete the
wp-contentfolder and thewp-config-sample.phpfile from the extracted copy so you don't overwrite your themes, plugins, and uploads. - Upload via SFTP: Upload the remaining files to your WordPress root folder and allow them to overwrite existing files.
With WP-CLI, you can do the same thing in one line. This reinstalls core files for your current version and leaves wp-content and wp-config.php alone:
wp core download --force --skip-content --version=$(wp core version)
You can also verify core file integrity against official checksums:
wp core verify-checksums
Step 7: Handle an Overloaded Database Server
If the error comes and goes, especially during busy periods, the database server may be running out of connections or memory. This is common on shared hosting and small VPS plans.
- Check for traffic spikes: A sudden surge, a bot attack, or a brute-force login attempt can exhaust connections.
- Reduce database load with caching: A page caching plugin like WP Rocket, W3 Total Cache, or WP Super Cache serves static pages without hitting the database on every request. An object cache such as Redis reduces repeated queries further.
- Clean up autoloaded options: Bloated
wp_optionstables slow every page load. Plugins like WP-Optimize can help clean up old transients and revisions. - Upgrade your plan: If your site has simply outgrown its hosting, moving to a plan with more resources is the long-term fix.
You can check how many connections your server allows and how many are in use:
SHOW VARIABLES LIKE 'max_connections';
SHOW STATUS LIKE 'Threads_connected';
If Threads_connected regularly approaches max_connections, you need caching, a higher limit, or more server resources.
Step 8: Restore From a Backup
If the database has been deleted, badly corrupted, or damaged by malware, restoring from a recent backup is the most reliable fix. Most managed hosts offer one-click restores from their dashboard. If you use a backup plugin such as UpdraftPlus, you can restore once you have a working WordPress install, or import the SQL file manually through phpMyAdmin.
With WP-CLI, importing a database backup looks like this:
wp db import backup.sql
If you suspect the site was compromised, restoring alone isn't enough. You also need to find and close the entry point, change all passwords, and replace the database credentials.
How to Prevent the Error From Happening Again
Once your site is back online, a few habits reduce the chance of seeing this error again:
- Keep regular off-site backups: Daily database backups stored somewhere other than your server give you a fast recovery path.
- Use uptime monitoring: Services like UptimeRobot or Jetpack's downtime monitor alert you within minutes when your site goes down.
- Update carefully: Test major plugin and theme updates on a staging site first.
- Use caching: Page and object caching reduce database load during traffic spikes.
- Choose reliable hosting: A host with good database performance and responsive support makes a big difference.
- Document your credentials: Keep your database name, user, and host in a password manager so you can check them quickly after any change.
FAQ: Error Establishing a Database Connection
Almost never. The error means WordPress can't reach the database, not that the database is gone. In the vast majority of cases, your posts and pages are intact and reappear once the connection is restored.
Migrations often change the database name, username, password, or host. If wp-config.php still contains the old values, WordPress can't connect. Update the four DB constants to match your new host's database details.
On most hosts it's localhost, but some use a dedicated hostname, an IP address, or a custom port. Check your hosting dashboard or documentation for the exact value.
No. The repair page can be accessed without logging in while that constant is set. Remove the line from wp-config.php as soon as you've finished repairing the database.
An intermittent error usually points to an overloaded database server that runs out of connections or memory during traffic spikes. Caching, cleaning up the database, and upgrading hosting resources are the typical fixes.
Indirectly, yes. A plugin that runs heavy queries or crashes during an update can corrupt tables or overload the server. However, simply deactivating plugins rarely fixes a pure connection error, because WordPress fails before plugins load.
Contact your host if your credentials test correctly but the connection still fails, if multiple sites on the account are affected, or if you don't have access to restart the database server yourself.
Conclusion
The "Error establishing a database connection" message looks serious, but it almost always comes down to a small number of fixable causes. Work through them in order: check your host's status, verify the credentials in wp-config.php, repair tables if the dashboard asks you to, confirm user privileges, replace core files if needed, and restore from a backup as a last resort.
Once your site is back, invest a little time in prevention. Regular backups, uptime monitoring, caching, and a reliable host mean that if this error ever shows up again, you'll know exactly where to look and have a quick path back online.


