Error Establishing A Database Connection: How To Fix It

Error Establishing A Database Connection: How To Fix It

One line of text on a white page, no header, no menu, no content: Error establishing a database connection. It is the most complete failure WordPress can show you, because what you are looking at is not really a WordPress page at all. It is the last thing WordPress can say before it gives up.

The good news is that this error has a short list of causes, and you can work through them in a sensible order rather than guessing. This guide covers what the message actually means, the five things that genuinely cause it, a two minute test that tells you which one you are looking at, and what to change so that it does not happen again.

What The Error Actually Means

A WordPress site is two things: the files, and the database. The files are the theme, the plugins and WordPress itself. The database holds everything those files exist to display, which is your posts, pages, products, orders, users, settings and comments.

Every time somebody loads a page, WordPress reads four values from wp-config.php, opens a connection to the database server using them, and asks for the content it needs. Those four values are the database name, the username, the password and the host. If any one of them is wrong, or the server at the other end does not answer, WordPress cannot build the page. It has no cached copy to fall back on and nothing sensible to show, so it prints the one line and stops.

That is why the error looks so severe. Your content is almost certainly fine. What has failed is the connection between the two halves of your site, and that is usually a smaller problem than the blank page suggests.

It is worth being clear about what this error is not. It is not a browser problem, so clearing your cache or trying a different browser changes nothing, which sets it apart from client-side errors such as ERR_CACHE_MISS. It is not a DNS problem either. And it is not by itself a sign that you have been hacked, though in a small number of cases it is a side effect of one, which we come back to below.

First: Is It The Whole Site, Or Just wp-admin?

Before changing anything, load your admin address, yoursite.com/wp-admin, and read what comes back. This single check splits the problem in half.

  • The same error on both the front of the site and the admin. WordPress cannot connect at all. The cause is the credentials, the database server, or a connection limit.
  • A different message in the admin, along the lines of One or more database tables are unavailable. The database may need to be repaired. The connection itself is working. A table is damaged, and the repair step below is what you need.

Those two paths barely overlap, so knowing which one you are on saves you from trying fixes that were never going to apply. The WordPress documentation on common errors makes the same split.

Cause 1: The Credentials Are Wrong

This is the most common cause by a wide margin, and it has a tell: the site was working, and then somebody changed something. A migration to a new host, a restored backup, a new database user, a rotated password, a staging copy pulled down to a local machine. The files arrived carrying the old details, and the database is now somewhere else or behind a different password.

Open wp-config.php in the root of your site, over SFTP or through your host's file manager. Near the top you will find these four lines:

define( 'DB_NAME', 'example_wp' );
define( 'DB_USER', 'example_wpuser' );
define( 'DB_PASSWORD', 'the-password' );
define( 'DB_HOST', 'localhost' );

Check each one against what your host's control panel says, character for character. Four things go wrong here more than anything else:

  1. The database name or user is missing its prefix. Many hosts prepend your account name, so the database you created as wp is really example_wp. Copying the value out of the panel removes the guesswork.
  2. The password contains a character that broke the line. A password with a straight apostrophe in it ends the PHP string early. Generate a new one without quote characters rather than fighting the escaping.
  3. DB_HOST is not localhost. On a good many hosts the database runs on its own server and the value is something like mysql.yourhost.net, sometimes with a port number. localhost is the default, not the rule.
  4. The user exists but has no rights on that database. Creating a user and granting its access are two separate steps in most control panels, and the second is easy to skip.

If you have just moved the site, this is nearly always the answer, and our guide to migrating WordPress to a new host sets out the order that avoids it. The wp-config.php reference documents every constant in the file, and the editing guide covers how to change it safely.

Cause 2: The Database Server Is Down Or Out Of Room

If the credentials have not been touched and the site simply stopped, the database server itself is the next suspect. MySQL and MariaDB stop accepting connections for a few blunt reasons:

  • The service has crashed or been stopped. Often after a server restart where it did not come back up with everything else.
  • The disk is full. A database that cannot write cannot serve. Log files and old backups are the usual culprits, and the symptom can appear well before the disk looks full to you.
  • The server ran out of memory and the operating system killed the database process to save itself. On small shared servers this is routine under load.

On shared hosting you can see none of this, which is exactly the frustration: your site is down and the cause is on the other side of a wall. Check your host's status page, then open a ticket and quote the error. On a VPS or a dedicated server you can look directly, and the service status plus the last hundred lines of the MySQL error log will normally tell you inside a minute.

This is also the case where the error comes and goes. An intermittent database error, especially at busy times, usually means the server is running out of something rather than that anything is misconfigured. It often travels with other symptoms, such as connection timed out errors on ordinary requests.

Managed Hosting solutions for WordPress backed by Speed, Security and Scalability

Talk To Sales →

Cause 3: A Corrupted Table

If the front of the site is broken but the admin tells you that tables are unavailable or may need repairing, one or more tables are damaged rather than missing. It normally follows an unclean shutdown, a crash part way through a write, or a disk that filled up mid-query.

WordPress has a repair tool built in, and it is deliberately switched off until you ask for it. Add this line to wp-config.php, above the line that says it has stopped editing:

define( 'WP_ALLOW_REPAIR', true );

Then visit yoursite.com/wp-admin/maint/repair.php. You do not need to be logged in, which is precisely why you must remove that line as soon as you have finished. Left in place, it lets anybody on the internet run repairs on your database.

Choose "Repair Database" first, and "Repair and Optimize" only if you have time, because optimising a large table locks it while it runs. If you have WP-CLI available, wp db check and wp db repair do the same job from the command line without touching the config file at all.

If neither gets you back, the table needs help at the database level with REPAIR TABLE, or restoring from a backup. Take a copy of the database before you run any repair, whatever state it is in. A damaged table you still hold is worth more than a repaired one you have lost half of.

Cause 4: Too Many Connections

Every database server has a ceiling on simultaneous connections, and hosts usually set a second, lower ceiling per user. Go past it and new connections are refused while existing ones carry on, which is why the site can be down for some visitors and fine for others, or down for a minute and back again without anybody doing anything.

The giveaway appears in the error log rather than on screen: Too many connections, or a message about max_user_connections being exceeded. Three things cause it more often than anything else:

  • A traffic spike that a shared plan was never sized for: being featured somewhere, or a campaign landing all at once.
  • A slow query holding connections open. One badly indexed query on a large table, usually from a plugin, keeps connections occupied for long enough that they stack up faster than they clear.
  • Bots and attacks. Aggressive crawlers and repeated login attempts on wp-login.php generate database work at a rate real visitors never would.

Raising the limit treats the symptom. The lasting fixes are page caching so that most visitors never reach PHP at all, finding the slow query, and being on a plan with headroom for the traffic you actually get. We cover the shape of that in hosting for high traffic WordPress sites.

Cause 5: Something Changed The Database Without You

The rarest group, but worth knowing about. A database user deleted during a tidy-up, a host suspension for non-payment or resource abuse, a control panel action that dropped the wrong database, or a compromise in which an attacker changed credentials or damaged tables.

The tell is that nothing you changed explains it, and the database or the user has genuinely gone rather than being unreachable. If you suspect a compromise, restore from a backup that predates it and change every password before the site goes back up, because putting the same site back with the same credentials simply replays the incident.

A Two Minute Test That Tells You Which One It Is

Rather than working through the causes in turn, you can ask the database server directly. Create a file called dbtest.php in the root of your site, using the four values copied out of wp-config.php:

<?php
$link = mysqli_connect( 'localhost', 'example_wpuser', 'the-password', 'example_wp' );
if ( ! $link ) {
    exit( 'FAILED: ' . mysqli_connect_error() );
}
exit( 'CONNECTED' );

Load yoursite.com/dbtest.php and read what comes back. The message is the diagnosis:

What you seeWhat it meansWhere to go next
CONNECTEDCredentials and server are both fineCorrupted table, or a limit being hit intermittently
Access denied for userWrong username or password, or no rights on that databaseCause 1
Unknown databaseThe name is wrong, or the database is goneCause 1, then Cause 5
Can't connect to MySQL serverNothing is answering at that hostCause 2, and check DB_HOST
Too many connectionsThe ceiling has been reachedCause 4

Delete the file when you are done. It contains your database password in plain text, and it is readable by anybody who guesses the address.

How To Stop It Happening Again

Most repeat incidents come down to four things, none of them exotic:

  1. Backups you have actually restored. A backup nobody has tested is a hope rather than a plan. Restore one onto a staging site occasionally and watch it come back.
  2. Caching, so the database is not asked the same question a thousand times. Page caching is the single biggest reduction in database load available to most sites.
  3. Monitoring that tells you before your visitors do. Uptime checks are cheap, and the first you hear of this error should not be an email from a customer.
  4. Headroom. If you hit connection limits on your best traffic days, the plan is the problem, not the traffic.

There is also a question of whose job it is. On unmanaged hosting, every cause above is yours to diagnose at the moment it happens, which tends to be the worst possible moment. On managed hosting the database server, its limits, its backups and its monitoring are the host's responsibility, and a good host notices the failure before you do. If you look after a number of sites, that difference compounds quickly, which we go into in managing multiple WordPress sites.

Whichever route you take, the routine in our WordPress maintenance checklist is what keeps the database side quiet: backups verified, plugins reviewed for the slow query problem, and enough disk space that it never fills.

FAQs

Will I lose my content because of this error?

Almost never. The error means WordPress cannot reach the database, not that the database has been emptied. Your posts, pages and orders are sitting where they were. The exception is a corrupted table, where a small amount of recent data can be lost in the repair, which is the reason to copy the database before repairing anything.

Why does the error come and go on its own?

An intermittent database error points at a limit rather than a mistake. Connections are refused once a ceiling is reached and accepted again as they free up, or the database server is running out of memory under load and recovering. Constant errors point at credentials or a stopped service; intermittent ones point at capacity.

How do I fix it if I cannot get into wp-admin?

Everything in this guide is done over SFTP or your host file manager, not from the dashboard. You edit wp-config.php to check the credentials, upload a small test file to ask the database directly, and add the repair constant if a table is damaged. None of it needs a working login.

Can a plugin cause an error establishing a database connection?

Indirectly, yes. A plugin cannot break your credentials, but one with a slow, badly indexed query can hold connections open until the limit is reached, which produces the error under load. Deactivating plugins by renaming the plugins folder over SFTP is a reasonable test once you have ruled out the credentials.

Whose responsibility is this, mine or my host?

It depends on the cause. Wrong credentials in wp-config.php are yours, usually after a migration or a password change. A crashed database service, a full disk on the server or a connection limit set too low for your plan are the host side. On managed hosting the whole database layer is the host job, including noticing the failure before you do.

Hosting That Keeps Up With Your Content

Every FastCow plan includes free SSL, a global CDN, daily backups and 24/7 expert support, set up for you.

View Packages
← Back to all articles