Understanding the Database Connection Error
If you have landed on this page, you are probably staring at a plain white screen with a single line of text: "Error establishing a database connection." No menu, no styling, sometimes not even your site's name. It is one of the most alarming messages in WordPress precisely because it gives you almost nothing to work with, and it can appear even when nothing about your site's content or design has actually changed.
Here is what is happening behind the scenes. WordPress is not really one program that renders your pages by itself. Every time someone visits a page on your site, WordPress asks a separate piece of software, the database, for the actual content: your posts, pages, settings, plugin configuration, and more. The database is usually MySQL or MariaDB, and it typically runs on the same server as your site, though on larger setups it can run on its own dedicated server entirely. When WordPress cannot reach that database, or the database refuses the connection, WordPress has nothing to build a page with. Rather than show a broken, half-rendered page, it shows this generic error instead.
That is also why the error is so unhelpful on its own. It tells you the connection failed, but not why. The database might be down. The credentials WordPress is using might be wrong. The database itself might have corrupted tables. Your hosting account might have hit a connection or resource limit. Or, less often but seriously, the site might have been compromised and the attacker's changes are interfering with normal database access. This guide walks through each of those causes and gives you a clear, ordered set of fixes so you are not guessing.
One reassuring fact before we go further: this error almost never means your content is gone. The database connection error is about WordPress reaching the database, not about the database being deleted. In the vast majority of cases we see, the underlying data is intact and the fix is a matter of restoring the connection or repairing a table, not rebuilding a site from scratch. Keep that in mind as you work through the steps below. Panic leads to rushed decisions, like restoring an old backup you did not need, so slow down and diagnose first.
It also helps to understand who is affected and when. If you manage a single small business site, this error typically means visitors, and potentially customers mid-purchase, cannot see any part of your site until it is fixed, which is why speed matters even as you stay methodical. If you manage several client sites, the same underlying cause, a host outage, a shared server hitting its connection limit, can sometimes affect multiple accounts at once, which is a useful clue in itself. Either way, the goal of this guide is to get you from "something is broken and I do not know why" to a specific, confirmed cause as quickly as possible, because a confirmed cause almost always has a fast and reliable fix.
Common Causes of the Error
Before touching any files, it helps to understand the usual suspects. In our experience fixing this error across many WordPress sites, the causes cluster around a handful of patterns. Knowing which one you are dealing with saves a lot of time.
Wrong database credentials in wp-config.php
Your site's wp-config.php file stores four pieces of information WordPress needs to reach the database: the database name, the username, the password, and the host. If any of these is wrong, missing, or was recently changed on the hosting side without updating the file, WordPress cannot log in to the database and throws this exact error. This is by far the most frequent cause we encounter, especially after a site migration, a host change, or a manual edit gone wrong.
Corrupted database tables
WordPress stores everything in a set of database tables. Tables can become corrupted for several reasons: an interrupted import, a server crash mid-write, a disk error, or a plugin that writes to the database in a way it should not. When a core table like wp_options is corrupted, WordPress may fail to connect properly even though the credentials are perfectly correct.
Database server down or overloaded
On shared hosting in particular, the database server can hit a maximum connection limit, especially during traffic spikes or when a plugin runs inefficient queries repeatedly. If the database process itself has stopped, crashed, or is refusing new connections because it is overwhelmed, every site sharing that server can show this error at the same time.
Corrupted core, theme, or plugin files
Less commonly, a corrupted WordPress core file, a bad plugin update, or a botched file transfer can interfere with how WordPress attempts the database connection in the first place, producing the same error message even though the database itself is healthy.
Exceeding host resource limits
Many hosting plans, particularly budget shared hosting, cap the number of simultaneous database connections or the amount of memory and CPU your site can use. If a traffic surge or a heavy plugin pushes you past that ceiling, the host may throttle or block new database connections until usage drops.
A hacked or compromised site
Occasionally the error is a symptom of a security incident. Malicious code can alter wp-config.php, add rogue database users, or overload the database with junk data and spam queries. If you notice this error alongside strange redirects, unfamiliar admin users, or unexpected files, treat it as a possible hack rather than a routine glitch. Our guide on how to fix a hacked WordPress site covers that scenario in depth.
The chart above is illustrative, not a scientific survey, but it reflects a real pattern: credential problems and server-side overload account for the bulk of cases, corrupted files and hacks are less frequent but more serious when they happen.
| What you see | Likely cause | Where to look first |
|---|---|---|
| Error shows on every page, including wp-admin | Wrong database credentials or database server unreachable | wp-config.php and hosting control panel |
| Front end broken but wp-admin loads with a different message about missing tables | Corrupted or missing database tables | phpMyAdmin, repair tool |
| Error appears only during busy periods | Too many database connections or a resource limit on shared hosting | Hosting resource usage graphs |
| Error appeared right after a migration or restore | Old database host, wrong table prefix, or incomplete import | wp-config.php DB_HOST and table prefix |
| Error appeared with no recent changes on your end | Host-side outage or maintenance | Host status page and support |
| Error appeared alongside strange redirects or unfamiliar admin accounts | Compromised site | User list and recently modified files |
Quick Checks Before You Troubleshoot
Before you start editing files, spend five minutes ruling out the easy explanations. This saves you from chasing a complicated fix when the real problem is simple and temporary.
- Reload the page after a minute. If your host is doing brief maintenance or your database server hit a momentary connection spike, the error can resolve itself within a minute or two. Try a hard refresh and, if possible, load the site from a different device or network in case the issue is local caching.
- Check whether wp-admin shows the same error. Try loading yoursite.com/wp-admin directly. If the front end shows the generic error but wp-admin shows a more specific message, such as one or more database tables being unavailable, that points toward a corrupted table rather than bad credentials, and you can skip ahead to the repair section.
- Check if other sites on the same hosting account are affected. If you host multiple sites and all of them show the same error at the same time, the problem is almost certainly on the server or database side, not something specific to one site's files.
- Look for a notice from your host. Many hosts send email or post status page updates about planned maintenance or unexpected outages. Check your inbox and your host's status page before assuming the fault is on your end.
- Check your error logs. Most hosting control panels expose a PHP error log or a raw access log. Look for lines mentioning "Error establishing a database connection," "Access denied for user," or "Can't connect to MySQL server." These give you a much more specific starting point than the generic front end message.
- Note what changed recently. Did you just migrate hosts, restore a backup, update a plugin, or edit wp-config.php by hand? The timing of the error relative to your last change is one of the strongest clues you have.
Once you have ruled out a temporary blip and confirmed the error is real and ongoing, move on to the structured fixes below in order. They are arranged from most common and easiest to check, to more involved.
Fix Your wp-config.php Credentials
Start here in almost every case. The wp-config.php file sits in your WordPress root directory, the same folder that contains wp-admin, wp-content, and wp-includes. You can access it through your hosting file manager, an FTP or SFTP client, or SSH if your host supports it.
Open the file and look for these four lines near the top:
define( 'DB_NAME', 'your_database_name' );
define( 'DB_USER', 'your_database_user' );
define( 'DB_PASSWORD', 'your_database_password' );
define( 'DB_HOST', 'localhost' );
What to check for each field
- DB_NAME must match the exact database name in your hosting control panel. A single typo, an extra character, or the wrong database if you have more than one on the account, will cause this error.
- DB_USER must be a database user that has been granted access to that specific database. Creating a database and creating a user are two separate steps on most hosts; the user also needs to be explicitly assigned to the database.
- DB_PASSWORD is case sensitive and easy to mistype when copying manually. If you recently reset this password in your hosting panel, this is almost certainly why the site broke; the file needs to be updated to match.
- DB_HOST is often "localhost," but not always. Some hosts require a specific hostname, an IP address, or a non-standard port appended after a colon. If you moved to a new host or a new server within the same host, this value frequently needs to change even if nothing else does.
Watch for invisible mistakes too: stray spaces before or after a value, straight versus curly quotation marks if the file was edited in a word processor instead of a plain text editor, and accidentally deleted semicolons. Any of these can break the line even though it looks correct at a glance.
Where to find the correct values
Log in to your hosting control panel, whether that is cPanel, Plesk, or a custom dashboard, and look for a database section, often labeled "MySQL Databases" or "Databases." There you can view existing database names and usernames, and reset a database user's password if you are not certain what it currently is. Resetting the password is usually safe and fast: reset it in the panel, then immediately update the matching value in wp-config.php so the two stay in sync.
If you manage several client sites, or you inherited a site without documentation, this is also a good moment to store credentials somewhere secure so you are not repeating this hunt every time something changes. If keeping track of hosting and database details for multiple WordPress sites has become a chore, our team can take that off your plate. Feel free to get in touch if you would rather hand this over to someone who manages it daily.
After updating any value, save the file, upload it back to the server if you edited it locally, and reload your site. If the credentials were the problem, the fix is immediate. If the error persists, move to the next section and test the connection directly.
Test the Database Connection Directly
If your wp-config.php values look correct but the error continues, the next step is to test the database connection outside of WordPress entirely. This isolates whether the problem is with WordPress itself or with the database and its credentials.
Create a small test script
Create a new plain text file named something like db-test.php with the following content, replacing the placeholder values with the exact values from your wp-config.php:
<?php
$link = mysqli_connect('DB_HOST_HERE', 'DB_USER_HERE', 'DB_PASSWORD_HERE', 'DB_NAME_HERE');
if (!$link) {
die('Connection failed: ' . mysqli_connect_error());
}
echo 'Connected successfully';
mysqli_close($link);
?>
Upload this file to your WordPress root directory using FTP, SFTP, or your hosting file manager, then visit yoursite.com/db-test.php in your browser.
Reading the result
- If you see "Connected successfully," the credentials and the database server are both working fine from PHP's perspective. That points the problem back toward WordPress itself: a corrupted table, a corrupted core file, or a plugin conflict rather than the connection settings.
- If you see a message like "Access denied for user," the username or password is wrong, or that user does not have permission on that particular database. Go back to your hosting panel, confirm the user is attached to the correct database, and reset the password if needed.
- If you see "Unknown MySQL server host" or a similar message, the DB_HOST value is wrong. Confirm the exact hostname your host expects; it is sometimes different from "localhost," especially on managed WordPress hosting or when the database lives on a separate server.
- If you see "Can't connect to MySQL server," or the page times out completely, the database server itself may be down, overloaded, or blocking connections from your site's server. This points toward the server-side issues covered later in this guide.
Important: delete db-test.php from your server as soon as you are done. Leaving a script like this in place, even briefly, exposes your database credentials to anyone who happens to find the URL, and search engines can index files faster than people expect. Treat it as a temporary diagnostic tool only.
This kind of targeted testing is exactly what separates a guess from a diagnosis. If you would rather have someone experienced run through this process for you, our WordPress support services include exactly this kind of troubleshooting, and you can always get a free quote if you want a second pair of eyes before you make any changes.
A note on shared versus dedicated database servers
On smaller hosting plans, your database typically lives on the same physical or virtual server as your website files, which is why DB_HOST is so often simply "localhost." As sites grow, many hosts move the database onto a separate, dedicated server for better performance and reliability, and in that setup DB_HOST becomes an internal IP address or a specific hostname the host provides you. If you have recently upgraded your hosting plan, migrated to managed WordPress hosting, or moved to a VPS, this is a common point where DB_HOST quietly changes and nobody remembers to update wp-config.php to match. Always check your hosting welcome email or knowledge base for the exact value they expect rather than assuming "localhost" will always work.
It is also worth testing connectivity using SSH if your host provides it and you are comfortable with the command line. Connecting with a command like mysql -u your_user -p -h your_host your_database gives you an even more direct read on whether the credentials and host are correct, independent of PHP entirely. If the command line connects but your site still shows the error, that tells you the problem is specific to how WordPress or PHP is handling the connection, not the database credentials themselves, which again points you back toward file corruption or a plugin conflict rather than wp-config.php.
Repair a Corrupted WordPress Database
If your test script connected successfully but the site still shows the error, or wp-admin showed a message about one or more database tables being unavailable, the next likely cause is a corrupted table somewhere in your database.
Using the built-in WordPress repair tool
WordPress includes a repair tool that is disabled by default for security reasons, since anyone who finds the URL could otherwise trigger it. To turn it on temporarily, add this line to wp-config.php, ideally just above the line that says "That's all, stop editing":
define( 'WP_ALLOW_REPAIR', true );
Save the file, then visit yoursite.com/wp-admin/maint/repair.php in your browser. You will see two buttons: one to repair the database, and one to repair and optimize it. Choose repair and optimize for a more thorough pass. WordPress will scan every core table, flag any that are corrupted, and attempt to fix them automatically.
Once the process finishes and your site loads normally again, go back into wp-config.php and remove the WP_ALLOW_REPAIR line, or at least change it to false. Leaving this tool permanently enabled is an unnecessary risk since it requires no login to use.
Repairing tables manually through phpMyAdmin
If the built-in tool does not resolve the issue, or you prefer more visibility into what is happening, phpMyAdmin gives you direct access to the database.
- Log in to your hosting control panel and open phpMyAdmin.
- Select your WordPress database from the left sidebar.
- You will see a list of tables, each typically prefixed with something like wp_ unless it was customized during installation. Look at the "Status" or "Overhead" column for anything unusual, or any table marked as "in use" or "crashed."
- Select all tables using the checkbox at the top, then choose "Repair table" from the "With selected" dropdown menu at the bottom of the list.
- Review the output. Tables that were fine will show "OK." Tables that needed work will show what was done.
If a specific table repeatedly shows as corrupted even after repair, note which one it is. Some plugins create their own tables for logs, analytics, or cache data, and those are usually safe to repair or even empty without affecting your actual content, since they regenerate automatically. Core tables like wp_posts, wp_postmeta, wp_options, and wp_users are the ones that matter most and deserve careful attention if they are affected.
When repair does not fix it
Occasionally a table is too badly damaged for a standard repair to fix, particularly after a hard server crash or a failed migration. In that case your options are restoring the table from a backup, or, if you understand the table structure, manually recreating it, which is not something we recommend attempting without experience given how easy it is to make things worse. This is a reasonable point to reach out for help rather than keep experimenting on a live site.
Check If MySQL Is Down or Overloaded
If your test script itself failed to connect, meaning the problem is not your WordPress files but the database server response, the issue sits on the server side. This is common on shared hosting where many sites share the same database server and its finite resources.
Signs the database server itself is the problem
- The error appears across multiple sites on the same hosting account at the same time.
- Your test script returns "Can't connect to MySQL server" rather than an access denied message.
- The error is intermittent, appearing during busy hours and clearing up later.
- Your host's status page mentions database or server issues.
Too many connections
Every database server has a maximum number of simultaneous connections it will accept. On shared hosting this limit is often set fairly low to keep the server stable for everyone on it. If your site, or a busy neighbor on the same server, opens more connections than the limit allows, you will see connection errors until some of those connections close. Heavy plugins, particularly ones that query the database inefficiently on every page load, are frequent culprits here. If your site has been getting slower generally and this error appears during traffic spikes, it is worth reading through our guide on how to speed up a WordPress website, since many of the same fixes that improve speed also reduce database load.
Checking service status
Most hosting control panels have a section showing server health, resource usage graphs, or a database service status indicator. Look for CPU, memory, or database connection graphs around the time the error started. A sharp spike right before the error began is a strong clue that you hit a limit rather than experienced a random failure.
What to tell your host
When you contact hosting support, give them specifics rather than just describing the symptom. Mention:
- The exact error message and where it appears (front end only, or wp-admin too)
- The results of your db-test.php script, including the exact error text it returned
- The approximate time the error started
- Whether other sites on the same account are affected
- Any recent changes: new plugins, a traffic spike, a migration
Good hosting support can check server-side logs you cannot see yourself, confirm whether the database process crashed, restart it if needed, and tell you whether you are approaching a plan limit that calls for an upgrade. If your current host is consistently vague, slow to respond, or this is not the first time you have had unexplained downtime, that pattern is worth taking seriously when you plan your next hosting decision.
Shared hosting versus managed WordPress hosting
It is worth pausing here to think about what tier of hosting you are actually on, since it shapes how much of this problem is within your control. On budget shared hosting, you are typically sharing database resources with many other accounts on the same physical server, and you have little visibility into what those other sites are doing to the shared database process. A single noisy neighbor running an inefficient plugin can, in theory, affect the connection limits available to your site even though your own site did nothing wrong.
Managed WordPress hosting, and mid-tier VPS or cloud plans, generally give you more isolated resources, better monitoring, and support staff who are more familiar with WordPress specifically rather than generic web hosting. If this error, or general slowness and instability, keeps recurring on a site that matters to your business, it is worth honestly weighing whether the hosting tier itself has become the bottleneck rather than any single misconfiguration. We are happy to review your current hosting setup and tell you plainly whether an upgrade or migration would help; reach out through our contact page and we can take a look.
Rule Out Corrupted Files or a Hacked Site
If credentials are correct, the connection test passes, tables show as healthy after repair, and your host confirms the server is running normally, but the error still will not go away, it is time to look at your files themselves.
Corrupted or incomplete core files
A partial upload, an interrupted update, or a bad file transfer can leave WordPress core files corrupted or missing without necessarily throwing an obvious PHP error first. The fix is straightforward: download a fresh copy of WordPress core matching your current version from wordpress.org, and replace the wp-admin and wp-includes folders entirely, along with the individual files in the root directory such as wp-load.php and wp-settings.php. Do not touch wp-content, since that folder holds your themes, plugins, and uploads. This process replaces anything that might be damaged without affecting your actual content or configuration, since wp-config.php also lives outside the folders you are replacing.
A recently updated or conflicting plugin
If the error started right after updating a plugin, deactivate that plugin, and any others updated around the same time, by renaming its folder inside wp-content/plugins through FTP or the file manager. Renaming the folder forces WordPress to treat it as inactive without needing admin access, which matters when wp-admin itself is not loading. If the site recovers once that plugin is deactivated, you have found your cause, and you can look for an updated, compatible version or a replacement plugin.
Signs of a compromised site
Take this seriously if you notice any of the following alongside the database error:
- Unfamiliar administrator accounts in your user list, or existing accounts whose email addresses have been changed
- New files in wp-content or the root directory with strange names, or existing core files with recent modification dates you did not create
- Your site redirecting visitors to unrelated pages, or search results showing content you never published
- Your host warning you about malware, sending excessive email, or unusual outbound traffic from your account
- A wp-config.php file that has been altered to point at a database or credentials you do not recognize
An attacker who has gained access to your site can absolutely cause a database connection error, whether by injecting code that breaks normal operation, flooding the database with junk queries, or deliberately altering your configuration to cause disruption or extract data. If any of these signs are present, stop troubleshooting the connection error in isolation and treat this as a security incident. Our detailed guide on how to fix a hacked WordPress site walks through cleanup, and our article on how to secure a WordPress website covers the hardening steps that prevent a repeat. In cases like this, we generally recommend involving someone experienced early rather than late, since an incomplete cleanup can leave a backdoor in place that causes the same problem again within weeks.
Restore, Prevent, and Know When to Call a Developer
Restore from a backup if nothing else works
If you have worked through the steps above and the site is still broken, or the damage to the database is more extensive than a simple table repair can fix, restoring from a backup is a legitimate and often faster path back to a working site. Before you restore anything, confirm a few things first: how recent the backup is, whether it includes both files and the database or just one, and whether you are restoring to the same hosting environment or a new one.
Most hosts keep automatic backups for a rolling window, often accessible from the hosting control panel without needing a plugin at all. If you use a backup plugin, check its storage location, whether that is cloud storage, a remote server, or local storage on the same account, since a purely local backup does not help if the whole server was affected. Wherever possible, restore to a staging copy of the site first rather than directly overwriting the live site, so you can confirm the backup actually resolves the issue before committing to it. If you do not already have a staging environment, this is a good moment to set one up for future changes as well.
After restoring, immediately update wp-config.php with the correct current database credentials if you restored to a different server or host, since an old backup will contain the old values.
Preventing this error going forward
A handful of habits meaningfully reduce how often this error shows up:
- Keep a documented, working copy of your database credentials somewhere secure, separate from the live site, so you are not reconstructing them under pressure during an outage.
- Run regular, automated backups that include both files and the database, stored somewhere other than the same server, and actually test restoring one occasionally rather than assuming it works.
- Keep plugin and theme counts lean. Every additional active plugin is another piece of code that can query the database inefficiently or conflict with another plugin. Fewer, better maintained plugins generally means a more stable site, and it usually helps overall performance too, which our guide on speeding up a WordPress website covers in more detail.
- Choose hosting with headroom, not just the lowest available price. A plan that is already close to its resource or connection limits during normal traffic has very little tolerance for spikes, migrations, or plugin updates.
- Harden your login and file security so a hacked site is not adding "database connection error" to your list of problems on top of everything else. Our guide on securing a WordPress website is a solid starting checklist.
- Test major updates on staging first, including WordPress core updates, theme updates, and plugin updates, especially on any site where downtime has real business cost.
- Monitor uptime, so you hear about an outage from a monitoring tool within minutes rather than from a customer complaint hours later.
When to call a WordPress developer
Some situations are perfectly reasonable to handle yourself with the steps in this guide: a wrong password after a reset, a corrupted table that repairs cleanly, a brief host outage. Others are worth bringing in outside help, particularly when:
- You have worked through every fix above and the error persists with no clear cause
- You suspect a hack and are not confident you can find and remove every trace of it
- The site generates revenue or leads and every hour of downtime has a real cost to the business
- You do not have a recent, verified backup and are worried about making things worse
- The issue keeps recurring even after what seemed like a successful fix
If you recognize your situation in that list, it is often faster and less stressful to bring in a developer who has dealt with this exact error many times than to keep experimenting on a live, business-critical site. Our team handles this kind of troubleshooting regularly as part of our broader WordPress support and maintenance services, and we are happy to take a look at what is happening on your site. You can contact us directly to describe what you are seeing, or get a free quote if you want an idea of what ongoing support would look like so this kind of issue gets caught and fixed before it ever reaches your visitors.