Error Establishing a Database Connection in WordPress: Find the Cause, Then Fix It (2026)
Your WordPress site shows "Error establishing a database connection" and nothing else. Open /wp-admin/ to read which message you have, test the connection directly with PHP 8, and fix credentials, privileges, damaged tables or server limits safely.
Ali RehmanFreelance Web Developer
On this page 14 sections
yoursite.com/wp-admin/ and note the exact message you see there. That one detail decides which of the fixes below you need.WordPress keeps every post, page, setting and user in a MySQL or MariaDB database. Each time someone loads a page, WordPress logs in to that database, reads what it needs and builds the page. If the login fails, or the database answers with something unusable, WordPress stops and shows this error instead of a half-built site.
This guide explains what the error really means and how to tell the possible causes apart by the message you see. It then walks through the fixes in the order most likely to work, from a five-minute check of wp-config.php to repairing tables and dealing with hosting limits. It also covers what changes after a migration, how to rule out a hack, and whether a few hours of downtime will hurt your Google rankings.
What "Error establishing a database connection" actually means
“Error establishing a database connection” means WordPress couldn’t get a working response from its database. Usually the login details in wp-config.php are wrong, the database server is down or refusing connections, or the WordPress tables are damaged or missing. Your files and content are usually intact.
Under the hood, WordPress opens the connection in its database class (wpdb). If that fails, WordPress records a detailed explanation, roughly “the username and password information in your wp-config.php file is incorrect, or contact with the database server could not be established.” It then stops loading the page. The page is sent with an HTTP 500 status, so browsers, uptime monitors and search engines all see it as a server error.
The useful part is that WordPress doesn’t show everyone the same message.
First, find out which message you actually have
WordPress’s core code (the dead_db() function) gives visitors on the front end a short message: just the heading “Error establishing a database connection”. In the admin area it shows the full stored error. So the same broken site can show two different messages, and the wp-admin one is far more useful.
Visit /wp-admin/ and match what you see to the right starting step:
- Front end and wp-admin both show the error, and wp-admin adds “This either means that the username and password…”: WordPress can’t log in to the database server at all. Check Step 1 (
wp-config.phpvalues), then Step 2 (connection test). - wp-admin says “One or more database tables are unavailable. The database may need to be repaired.”: The login works, but WordPress can’t read its core tables. Go straight to Step 4 (repair) and skip the credential checks.
- The WordPress installation screen appears instead of your site: WordPress connected to a database that has no WordPress tables — wrong
DB_NAME, wrong$table_prefix, or an import that never finished. Check Step 1 and the migration checklist. - The error comes and goes, often at busy times: The database server is overloaded or hitting its connection limit. Go to Step 5.
- “Error reconnecting to the database”: The connection opened, then dropped partway through the request. Go to Step 5.
- A custom-designed error page: Someone added a
wp-content/db-error.phpdrop-in, which WordPress loads in place of its own message. Read it, then work through the steps as normal.
One more trap: a page cache or CDN can keep serving cached copies of your pages, so the home page looks fine while uncached pages and wp-admin are broken. Always test in a private window with a URL that can’t be cached, such as /wp-admin/ or /?nocache=1.

Before you change anything
Two minutes now can save you hours later.
- Download a copy of
wp-config.phpthrough your host’s File Manager or SFTP before you edit it. Every fix below that involves editing starts with this file. - Write down what changed recently. A migration, a password change in your hosting panel, a hosting plan change, a plugin installed just before the outage, or a traffic spike. Most cases of this error follow one of these.
- Check your host’s status page. If the provider has a database outage, nothing you change will help, and you could create new problems while you wait.
Step 1: Check the four database values in wp-config.php
According to the WordPress documentation on common errors, this error is usually caused by a mistake in wp-config.php. Open the file in the root folder of your site and find these four lines:
define( 'DB_NAME', 'example_wp' );
define( 'DB_USER', 'example_user' );
define( 'DB_PASSWORD', 'your-database-password' );
define( 'DB_HOST', 'localhost' );Now compare each value with what your hosting panel says. In cPanel, open MySQL Databases: it lists your databases, your database users, and which users are assigned to which database. Other control panels have an equivalent screen. Many cPanel hosts prefix names with the account name (for example acct_wp), so check the full name, not just the part you remember.
DB_HOST isn’t always "localhost"
On many shared hosts the database runs on the same machine, so localhost is correct. Managed and cloud hosts often use a separate database server instead, with a hostname, an IP address or a non-standard port. WordPress accepts several formats in DB_HOST, as shown in its parse_db_host() code:
- A hostname or IP:
localhost,127.0.0.1,db.example-host.net - A host with a port:
127.0.0.1:3307(port 3306 is assumed if you don’t add one) - A socket path:
localhost:/var/run/mysqld/mysqld.sock
If you moved hosts and copied the old wp-config.php across, DB_HOST is often the one value nobody updated.
Look for invisible mistakes
Many “the password is definitely right” cases are actually a typing problem:
- A space copied in at the start or end of the password.
- Curly “smart” quotes pasted in from a document or chat app instead of straight
'quotes. These usually cause a PHP error rather than this one, but check anyway. - A password containing a
'character, which ends the PHP string early. - A password changed in the hosting panel that was never updated in
wp-config.php.
If you’re unsure about the password, reset it for that database user in your hosting panel, paste the new value into wp-config.php, save the file and reload the page. The WordPress documentation suggests the same thing.
Step 2: Test the connection outside WordPress
If the values look right but the error remains, stop guessing and ask the database directly. WordPress hides the raw MySQL error from visitors, but a small PHP file can show it to you.
Create a file called db-test.php in the same folder as wp-config.php and paste in this code:
<?php
// Temporary database connection test. DELETE THIS FILE when you are done.
header( 'Content-Type: text/plain' );
$config = file_get_contents( __DIR__ . '/wp-config.php' );
function wp_config_value( $name, $config ) {
$pattern = '/define\(\s*[\'"]' . $name . '[\'"]\s*,\s*[\'"](.*?)[\'"]\s*\)/';
return preg_match( $pattern, $config, $m ) ? $m[1] : null;
}
$host = wp_config_value( 'DB_HOST', $config ) ?? 'localhost';
$user = wp_config_value( 'DB_USER', $config );
$pass = wp_config_value( 'DB_PASSWORD', $config );
$name = wp_config_value( 'DB_NAME', $config );
// Split "host:port" or "host:/path/to/socket" the way WordPress does.
$port = null;
$socket = null;
if ( str_contains( $host, ':/' ) ) {
[ $host, $socket ] = explode( ':', $host, 2 );
} elseif ( preg_match( '/^(.+):(\d+)$/', $host, $m ) ) {
$host = $m[1];
$port = (int) $m[2];
}
mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
try {
$db = new mysqli( $host, $user, $pass, $name, $port, $socket );
$tables = $db->query( 'SHOW TABLES' )->num_rows;
echo "Connected to database '$name' on '$host'.\n";
echo "Tables found: $tables\n";
} catch ( mysqli_sql_exception $e ) {
echo 'Connection failed (' . $e->getCode() . '): ' . $e->getMessage() . "\n";
}Open yoursite.com/db-test.php in your browser. The script reads the same four values WordPress uses and tries to connect with PHP’s mysqli extension. It then prints either a success message with the number of tables, or the exact error the database returned. It never prints the password. It needs PHP 8.0 or newer. If your wp-config.php loads values from environment variables instead of plain text, the regex won’t find them, so type the four values into the script temporarily instead.
db-test.php as soon as you’ve read the result. Leaving a file that tests database logins in your web root is a security risk.Here’s how to read the result:
- Connected, with a sensible table count: Credentials and server are fine. The problem is in the tables — go to Step 4.
- Connected, 0 tables: You’re connected to the wrong or an empty database. Check
DB_NAMEand confirm that the import finished. - 1045 Access denied for user: Wrong username or password, or the user can’t connect from this host. Check Step 1 again, then Step 3.
- 1049 Unknown database:
DB_NAMEdoesn’t exist under that name. Copy the exact name from your hosting panel. - 2002 / 2003 Can’t connect: Wrong host or port, or the server is down. Check
DB_HOSTand ask your host whether MySQL is running. - 2005 Unknown MySQL server host: The hostname in
DB_HOSTdoesn’t resolve. Use the host your provider documents. - 1040 Too many connections, or 1203 max_user_connections: The server is reachable but full. Go to Step 5.
These are standard MySQL error codes. The full list is in the MySQL server error reference and the client error reference.

Step 3: Check the database user, not just the password
There’s one case troubleshooting guides rarely cover: the username and password are correct, but the user isn’t attached to the database, or lacks the privileges it needs. This happens when someone recreates a database during a migration, or creates a new user and forgets the last step.
In cPanel’s MySQL Databases screen, scroll to Add User To Database, choose the user and the database, and grant All Privileges. Other control panels have a similar “assign user” or “permissions” option. If your host only allows remote database connections from approved IP addresses, as some cloud database services do, your web server’s IP needs to be on that list too.
Step 4: Repair damaged tables
If wp-admin says “One or more database tables are unavailable”, or the test connected fine, the login works and the tables are the problem. They may be damaged after a server crash, a full disk or an interrupted import.
Option A: WordPress’s built-in repair page. Add this line to wp-config.php, above the line that says “That’s all, stop editing!”:
define( 'WP_ALLOW_REPAIR', true );Then visit yoursite.com/wp-admin/maint/repair.php and choose Repair Database or Repair and Optimize Database. The WordPress wp-config documentation notes that you don’t need to be logged in to use this page, because a damaged database often makes logging in impossible. For the same reason, anyone can use it while the line is in place, so remove the line the moment the repair finishes.
Option B: WP-CLI. If you have SSH access, run wp db check to see the state of the tables, then wp db repair. Both wp db check and wp db repair run MySQL’s mysqlcheck tool with the credentials from wp-config.php, so the server needs the mysqlcheck (or mariadb-check) program installed.
Option C: phpMyAdmin. Select all the tables, then choose Repair table from the menu.
Repair works well for some types of damage, mainly with older MyISAM tables. Modern InnoDB tables usually report that repair isn’t supported. If repair doesn’t help, restoring the database from a backup made before the problem started is the safer next step, but be aware it removes anything published since that backup was made.
Step 5: When the server itself is the problem
If your values are correct and the test reports “can’t connect”, or the error comes and goes, the cause is probably outside WordPress. The WordPress documentation lists two hosting causes: the database has gone over its quota and been shut down, or the server is down.
The third common cause is connection limits. MySQL’s documentation on “Too many connections” explains that this means every allowed connection is already in use, up to the max_connections setting. Shared hosting plans often set a lower limit for each account. Each PHP process serving a page holds a connection, so traffic spikes, aggressive bots, slow database queries from heavy plugins, and many uncached admin or WooCommerce requests can all use up the limit. The error then appears for a few minutes and goes away again.
What helps:
- Page caching, so most visitors never trigger a database query. My guide to speeding up a WordPress site covers which caching layers matter.
- Finding the plugin that runs slow or heavy queries, using a query monitoring plugin on a staging copy of the site.
- Rate-limiting bad bots at your firewall or CDN.
Send your host specific questions, not just “my site is down”:
- Was the MySQL service down or restarted at [time of error]?
- Is my database over its size quota?
- What are my
max_user_connectionsandmax_connectionslimits, and did I hit them? - Can you share the MySQL error log for that time window?
If the limits keep getting hit even with caching in place, the hosting plan is probably too small for the site. My guide to choosing web hosting explains what to compare when you upgrade.

After a migration: five things to check
Most moves to a new host or domain that end in this error come down to one of these:
- 1
wp-config.phpvalues from the old host.DB_NAME,DB_USER,DB_PASSWORDand especiallyDB_HOSTmust match the new server. - 2The user isn’t assigned to the new database (Step 3).
- 3
$table_prefixdoesn’t match the imported tables. If the tables are namedwp7x_posts, the prefix must bewp7x_. A mismatch sends WordPress looking for tables that don’t exist. - 4The import didn’t finish. A database dump that timed out partway leaves you with only some tables. Compare the table count with the old server.
- 5DNS still points to the old server. If the old host has closed your account, the domain may be loading a dead installation. Check where your domain’s A record points.
If you change domains, update URLs with a tool that handles serialized data safely, such as wp search-replace. Don’t run plain SQL find-and-replace across every table.
Could the site have been hacked?
Sometimes. WordPress’s own troubleshooting documentation lists a compromised site as a possible cause. Suspect a hack if wp-config.php contains code you don’t recognise (long encoded strings, eval(, base64_decode(), the database password changed without anyone on your team changing it, or you see strange files in the root folder. In that case, fixing the connection isn’t enough. Change the database password and WordPress salts, scan the site and follow a proper cleanup process. My website security guide for small businesses covers the layers to put in place afterwards.
Will this error hurt my Google rankings?
A short outage usually won’t. Google’s documentation on HTTP status codes says 5xx errors make Googlebot temporarily slow down crawling. Pages already in the index stay there at first, but URLs that keep returning server errors are eventually dropped. Fixing the problem within hours matters much more than anything else you do for SEO. Once the site is back, check the Pages report in Search Console for server errors from the outage period.
Prevent the next one
- Keep automatic offsite backups of both files and database, and test a restore at least once.
- Store database credentials in a password manager, and update
wp-config.phpstraight away whenever someone changes them in the hosting panel. - Use uptime monitoring so you hear about an outage before your customers do.
- Keep caching on, remove plugins nobody uses, and review the hosting plan when traffic grows.
- Never leave
WP_ALLOW_REPAIRor test scripts on a live server.
A maintenance plan should cover these routinely. My breakdown of website maintenance costs shows what’s normally included.
Frequently asked questions
Will I lose my content because of this error?
Usually not. The error means WordPress can’t reach the database, not that the database has been deleted. Content is only at risk if the tables themselves are badly damaged, and even then a recent backup is the safety net.
Why does the error only show on some pages?
A page cache or CDN is probably serving stored copies of the pages that look fine. The live site is failing behind the cache. Test /wp-admin/ in a private window to see what’s really happening.
My credentials are correct. Why does it still fail?
Check that the user is assigned to the database with full privileges, that DB_HOST is right for your host (not always localhost), and that the server isn’t refusing connections because of a limit. The test script in Step 2 tells you which of these it is.
Is it safe to leave WP_ALLOW_REPAIR enabled?
No. The repair page works without logging in, so anyone could use it. WordPress’s documentation says to enable it only when you need it and disable it once the issue is solved.
Can a plugin cause this error?
Rarely, and not directly. A plugin can’t change your credentials, but heavy or badly written plugins can overload the database and cause “too many connections” errors on smaller hosting plans.
Can I show a nicer page while I fix it?
Yes. If a file called db-error.php exists in wp-content, WordPress loads it instead of its default message. A short “we’ll be back shortly” page with your contact details is better for customers than a blank error.
When to hand it over
If you’ve checked the four values, run the test, repaired the tables and the site still won’t connect, or if anything points to a hack, it’s time for someone with server access to take a look. Changing settings at random on a broken site usually makes recovery harder.
I help small businesses get WordPress sites back online and keep them stable through my website maintenance and fixes service. Everything is handled in writing: send the exact error message, what changed recently and your hosting provider through the project brief form, and I’ll tell you what I’d check first. For other WordPress symptoms, the WordPress troubleshooting hub sends you to the right guide. If you see “There has been a critical error” instead, follow the critical error guide.
Written by
Ali Rehman - Freelance Web Developer
I work on WordPress websites, practical fixes and scoped web applications. Read my background and skill scope, or send a project brief to discuss a written plan and quote - start here.
More articles by Ali Rehman →