The message “Error establishing a database connection” means one specific thing: PHP ran, WordPress started to load, and the first job it needed, opening a working conversation with the database server, did not happen. Your files are there, the web server is answering and wp-config.php was read. What is missing is the link between WordPress and MySQL or MariaDB, where every post, page, setting, user and order lives. Without it WordPress cannot even work out which theme to load, so it stops and prints one line.
The trouble is that the line is deliberately vague, and the same words cover causes that have nothing in common. A wrong password typed into a config file produces it. So does a database server that the operating system killed for using too much memory, a shared host that throttled an account for going over its limits, a table damaged by a crash, or a hostname that stopped resolving after a migration. The right fix for one is useless or harmful for another. Resetting a password during a server outage wastes your best minutes. Running a repair on a pure connection problem does nothing. Restoring a backup to cure a typo in wp-config.php throws away every order and comment written since that backup.
The idea that runs through this guide is simple: the error is a symptom, it has five families of cause, and your job is to find out which family you are in using the cheapest and safest checks first, in an order that can never make things worse. Read-only checks come before anything that writes. A copy of the current state comes before anything that changes data. One change at a time comes before any combination of fixes. Follow that discipline and most cases are solved in minutes, and the rest reach your host with enough evidence that they can solve them quickly too.
Here is the route. First, how WordPress produces the message and what the look-alike messages mean. Then the five families, a decision tree from symptom to likely cause, the first safe checks and how to read the evidence WordPress, PHP and MySQL leave behind, including the numeric error codes that name the real cause. Each family then gets its own section: credentials in wp-config.php, a wrong host or port or socket, a database server that is down or starved, host limits and query load, and corrupted tables including the WP_ALLOW_REPAIR repair page. The last sections cover restoring from a backup safely, what to ask your host, how to behave during an outage and how to stop it happening again.
A word on tools. Commands shown are standard MySQL, MariaDB, WP-CLI or Linux syntax, to be adapted rather than pasted blindly. Hosting control panels differ a great deal, so panel steps are described by goal and by where to look, not by button names. Throughout, imagine one example: a WooCommerce store with around 800 products on a shared plan that worked yesterday and shows the error today. That is an illustration, not data.
Key points
- The message means WordPress could not complete a connection to the database server, and that single symptom covers five unrelated families of cause.
- Run read-only checks first: compare the front end with wp-admin, check whether other sites on the same server fail, and try a separate client with the same credentials.
- A tiny standalone connection test and the numeric MySQL error code tell you far more than the WordPress page ever will.
- WP_ALLOW_REPAIR only helps with damaged tables whose engine supports repair, and the repair page needs no login while the constant is set, so remove it the moment you are done.
- Copy the current state before any repair or restore, because a restore swaps a broken site for lost orders and comments written after the backup.
- Most recurrences trace back to resource pressure, so page caching, query review, monitoring and a tested backup matter more than any one-off fix.
What the error message really tells you
Start with where the message comes from, because that tells you what it can and cannot mean. Every WordPress request, whether a visitor opening your home page or you opening wp-admin, begins the same way. The web server hands the request to PHP. PHP runs the WordPress loader, which reads wp-config.php. That file defines the constants that describe the database: its name, the user, the password and the host. Then WordPress creates its database object, called wpdb, and the constructor immediately tries to open a connection using PHP’s mysqli extension. If that attempt fails, WordPress stops and prints the message.
Two consequences follow from that timing. First, the connection is made very early, before any plugin or theme code runs. That is why the page looks the same on every WordPress site regardless of design: WordPress has not yet read the option that names your active theme, because options live in the database. It also means a plugin cannot produce this exact message by being buggy in PHP, since a plugin bug normally gives a white screen or the critical error notice. A plugin can still cause a connection error indirectly, by eating server resources or by editing wp-config.php.
Second, the message is a summary, not a diagnosis. The failure can happen at several distinct points: the server is not running, the address does not answer, the server answers but has no free connection slot, the username and password are refused, or the login works but the database cannot be used. WordPress collapses all of these into one heading. Depending on your debug settings you will see either that single line or a longer version that lists the usual suspects: the username and password, the hostname and whether the database server is running, naming the host WordPress tried to reach. Even the longer text is a list of suspects, not a finding.
The page normally comes with an HTTP server error status. You can confirm that by running curl -I followed by your own address, which prints only the response headers. It matters for monitoring, because a page that shows an error while returning a success code is much harder to detect.
Finally, learn the look-alikes, because each one points somewhere different:
- A message saying WordPress reached the server but could not select the database means the login worked. The database name or the user’s privileges are wrong.
- A message that your PHP installation appears to be missing the MySQL extension means PHP is misconfigured, often right after a PHP version change.
- A message that one or more database tables are unavailable and may need repair means the connection works and the damage is inside the database.
- A page saying the site is briefly unavailable for scheduled maintenance is the update system’s maintenance mode, not a database failure.
- The generic critical error notice is a PHP fatal error, which needs a different diagnosis entirely.
Where the error sits in a WordPress request
- Request arrivesThe web server passes the URL to PHP.
- wp-config.php is readDatabase name, user, password and host become constants.
- wpdb is createdWordPress builds its database object and connects at once.
- Connection attemptPHP’s mysqli extension tries a socket or a TCP port.
- Login and database selectionThe server checks credentials, then the database name.
- Failure stops hereWordPress prints the error. Plugins and themes never load.
- Success continuesOptions are read, then the theme and plugins load.
The five families of causes
Every case of this error falls into one of five families. Knowing them up front means you use cheap checks to rule families in or out instead of trying fixes at random. The figure lists the six gates a connection must pass, and each family owns one or more of them.
Family one: credentials. WordPress knocks on the right door but the login is refused. The name, user or password in wp-config.php is wrong, the user was never granted access to that database, or the password was changed on the server side while the file still holds the old one. This family is common after a manual edit, a migration, a host-side password reset or a staging push that copied the wrong config file. The signature is a failure that is constant from the first request, not one that comes and goes.
Family two: the server is down or starved. The MySQL or MariaDB process is stopped, crashed, killed by the operating system for using too much memory, unable to start because the disk is full, or running but out of connection slots. The signature is that every site on the same server fails and the database tool in your control panel fails too.
Family three: host limits. On shared and many managed plans your account has a ceiling on simultaneous database connections, CPU, memory or input and output. Cross it and the host refuses new connections even though the server is healthy. The signature is intermittency that follows traffic, cron jobs, backups or bots, while neighbouring accounts work fine.
Family four: corrupted tables. The connection works, but a damaged or missing table breaks the queries WordPress runs next. Depending on which table is damaged, WordPress reports that tables are unavailable, and some setups show the connection error on the front end. The signature is a recent crash, full disk or forced shutdown, plus a different message in wp-admin.
Family five: wrong host, port or socket. The credentials are right, but WordPress is knocking on the wrong door. After a migration the database may live on a separate host name instead of localhost, on a non-default port, behind a firewall, or reachable only through a specific socket file. The signature is that the failure starts exactly at a change and the test errors are network-type errors, not “access denied”.
Which family is likeliest depends on history, not statistics. A site you just migrated or whose wp-config.php was just edited points to families one and five. A sudden failure on a long-stable site where neighbours are also down points to two. An error that comes and goes under load points to three. A failure right after a crash or a full disk points to four. Two families can overlap, which is why you verify each gate rather than stopping at the first plausible cause.
Six gates every connection must pass
The first five minutes: safe checks that change nothing
The first minutes decide whether you fix this quickly or make it worse. Rule one: do read-only checks before anything that writes. Rule two: change one thing at a time and note the time. Rule three: do not run the installer, delete plugins, reinstall WordPress or restore a backup until the evidence says you need to. Each of those is a sensible repair for some problem, and each is destructive for this one when the real cause is a typo in a config file.
Work through these checks in order:
- Confirm the scope. Load the home page, a deep URL and the wp-admin login in a private window, ideally also from a phone on mobile data. That rules out your own browser cache and local DNS. Note whether the error is constant or comes and goes between refreshes.
- Compare the front end with wp-admin. The two should fail identically when the connection itself is broken. If wp-admin shows a message about damaged or unavailable tables, the connection works and you are in the corrupted-tables family. If it shows a message about selecting the database, the server and password are fine and the name or privileges are wrong.
- Look at the host. Check the provider’s status page, your inbox for maintenance or resource notices, and any banner in the control panel. A suspension for resource overuse or an unpaid invoice answers the question in seconds.
- Check neighbours. If you run other sites on the same account or server, even a test site, see whether they fail too. All failing points to the server or the account. Only one failing points to that site’s credentials or tables.
- Try a separate client. Open the database tool your host provides, such as phpMyAdmin or an equivalent. If it connects and lists your tables, the server is up and the database exists. Be careful with the conclusion: panel tools often log in with a privileged account, so this does not prove that the user named in wp-config.php can log in.
- List what changed. Think of any update, PHP version switch, migration, staging push, password reset, traffic spike, import or scheduled job in the last day.
Before you touch anything, take a safety copy. Download wp-config.php. If your panel offers a snapshot or an on-demand backup, take one now, even though the site is broken. A snapshot of the broken state is cheap insurance, because repairs and restores can destroy data you later want.
These checks take minutes and usually place you in a family already. The decision figure turns the most useful one, what wp-admin shows, into a rule of thumb.
What does wp-admin show?
Reading the evidence: logs, debug mode and error codes
The WordPress page hides the one detail that matters: what the database server actually said. That detail exists in three places, and it is worth reading them in this order.
First, WordPress’s own debug log. Add these lines to wp-config.php above the comment that tells you to stop editing:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
With WP_DEBUG on, WordPress typically lets PHP report the connection warning instead of silencing it, and WP_DEBUG_LOG writes it to wp-content/debug.log without showing it to visitors. The line you want is a warning from the mysqli extension that ends with an error number and a short message such as access denied or connection refused. Two cautions: debug.log often sits at a predictable, web-readable address and can contain file paths, so delete it or block access when you are done, and switch all three constants back off afterwards.
Second, the logs your host keeps. A control panel usually exposes the PHP error log for the site. On a server you control, the database server’s own error log records crashes, out-of-memory restarts, disk errors and aborted connections. If you do not know where it is, a logged-in administrator can ask the server:
SHOW VARIABLES LIKE 'log_error';
Third, a direct connection test, shown in the next sections, which returns the error number without WordPress in the way.
Learn to prefer the number over the wording. MySQL error numbers are stable across versions and hosting languages, while the wording shifts. The figure maps the ones you will meet most. Underneath all of them sits the single most useful distinction in this whole diagnosis: “access denied” means you reached the server, and “cannot connect” means you did not. An access error proves the server is running, the address is right and a slot was available, so families two, three and five are largely ruled out and you should look at credentials. A cannot-connect error means no one ever checked your password, so changing it cannot possibly help.
One more number deserves a mention. A “got error 28 from storage engine” message means the disk that holds the database has no space left, a cause that looks like a mysterious outage until you check the disk. Likewise, an error naming a table that is marked as crashed points at family four, not at anything in wp-config.php.
Common MySQL error numbers and what they point to
| What it usually means | Where to look first | |
|---|---|---|
| 1045 | Access denied for that user, password or source host | Credentials in wp-config.php, the user’s allowed host |
| 1049 or 1044 | Unknown database, or no rights on it | Database name, prefix and the user’s privileges |
| 2002 | Cannot connect through the local socket | Server stopped, or wrong socket path with localhost |
| 2003 or 2005 | Cannot reach the host, or the name does not resolve | Host, port, firewall, DNS, server stopped |
| 1040 | Too many connections on the whole server | Load, slow queries, PHP worker counts |
| 1203 or 1226 | A per-user connection or resource limit was reached | Account limits on the host, ask the provider |
| 2006 or 2013 | Server gone away or connection lost | Restart, crash, memory kill, timeouts |
| 1194 or 1195 | A table is marked as crashed | Corrupted tables and repair |
Family one: credentials and wp-config.php
If the evidence says access denied or unknown database, you are in the first family. Four constants in wp-config.php must agree with what exists on the database server:
define( 'DB_NAME', 'example_wpdb' );
define( 'DB_USER', 'example_wpuser' );
define( 'DB_PASSWORD', 'p4ss\'word-with-a-quote' );
define( 'DB_HOST', 'localhost' );
Check them against the source of truth, which is the database section of your host’s control panel. It lists the databases, the users and which user is attached to which database. On many hosts the names carry a prefix such as the account name, so the database is example_wpdb rather than wpdb. A user can exist and still have no rights on the database. Attaching the user with the privileges WordPress needs, normally all privileges on that one database and none elsewhere, is a separate step that is easy to miss.
These are the usual ways the four values go wrong:
- A password changed on one side only. The panel or the host reset it, and wp-config.php still holds the old one.
- Invisible characters. A trailing space or line break copied along with the password.
- Quoting. The password sits inside a single-quoted PHP string, so a single quote or backslash in it must be escaped with a backslash, as in the example. A long password of letters and digits avoids the problem.
- Duplicate definitions. PHP ignores a second define of the same constant, so an old DB_PASSWORD higher in the file beats your fix lower down.
- The wrong file. A migration or staging tool copied wp-config.php from another environment, or the configuration reads from environment variables and your edit is never consulted.
To see what WordPress is really using without hunting through files, WP-CLI can print constants straight from the configuration:
$ wp config get DB_NAME
$ wp config get DB_USER
$ wp config get DB_HOST
A ten-line script settles the question without WordPress in the way. Fill in the four example values with the real ones, save it as db-test.php next to wp-config.php, open it once in a browser, read the result and delete the file at once. It holds your password in plain text, so never leave it on the server and never commit it.
<?php
mysqli_report( MYSQLI_REPORT_OFF );
$link = mysqli_connect( 'localhost', 'example_wpuser', 'example_password', null, 3306 );
if ( ! $link ) {
echo 'Connect failed: ' . mysqli_connect_errno() . ' ' . mysqli_connect_error();
exit;
}
echo 'Connected. ';
echo mysqli_select_db( $link, 'example_wpdb' ) ? 'Database selected. ' : 'Select failed: ' . mysqli_error( $link ) . ' ';
$result = mysqli_query( $link, 'SELECT 1' );
echo $result ? 'Query OK.' : 'Query failed: ' . mysqli_error( $link );
mysqli_close( $link );
Read the result like a gate check. A connect failure with a number from the table above names the family. “Connected” but a failed selection means the name or privileges. All three lines passing while WordPress still fails means WordPress is reading different values than your script, so look for a second config file or an environment override. Reset the database password only when the evidence points at credentials, and change the panel and wp-config.php in the same minute.
Family five: wrong host, port or socket
DB_HOST accepts more than a bare name. It can be localhost, a host name supplied by your provider, a host name followed by a colon and a port number, or localhost followed by a colon and the path to a socket file. WordPress splits the string and passes the pieces to the mysqli extension. Many shared hosts keep the database on the same machine and use localhost. Others use a separate cluster and give you a long host name, shown in the panel next to the database. Migrating between the two kinds with an unchanged wp-config.php is a classic cause.
The subtle part is what “localhost” means. In MySQL clients, and in PHP’s mysqli, localhost normally means a local Unix socket file, not a TCP connection. Using 127.0.0.1 forces TCP instead. The two can behave differently: localhost can fail when the socket file lives somewhere PHP does not look, after a change in how PHP or the database was packaged, while 127.0.0.1 works. The reverse happens when the server has networking turned off and accepts only the socket. Swapping one for the other is a quick, reversible experiment, as long as you change only that value and put it back if nothing improves.
Ports and remote databases add more ways to fail:
- Non-default ports. The usual port is 3306, but some hosts and local tools use another. Put it after the host name with a colon.
- Allowed source hosts. A MySQL account is defined as a user at a source address. If the database is remote and the web server’s outgoing address changes, for example after a cloud move, the old rule no longer matches and you get an access error naming the new address.
- Firewalls and security groups. The database port must be open from the web server, and the server must be listening on a network interface, not only on the socket.
- DNS. A host name that no longer resolves produces a lookup failure in the log. Prefer the provider’s own database host name over one built from your domain.
- Containers. In Docker Compose, the host is the service name of the database container, never localhost, and the database may start a little later than the web container.
Some managed database offerings require encrypted connections. WordPress supports a client flag constant for this, which you set in wp-config.php before the line that stops editing. Check your provider’s documentation for the exact flag and certificate requirements before relying on it:
define( 'MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL );
When every value looks right, run the standalone test script from the previous section with the same host and port WordPress uses. If it also fails with a cannot-connect error, the problem is the route between web server and database, not WordPress, and it belongs with the host or whoever manages the network.
localhost versus 127.0.0.1 or a host name
| DB_HOST is localhost | DB_HOST is 127.0.0.1 or a host name | |
|---|---|---|
| Transport | Normally a local Unix socket file | A TCP connection through the network stack |
| What breaks it | Missing or misplaced socket file, server stopped | Closed port, firewall, DNS failure, networking disabled |
| Reachable from another machine | No, local only | Yes, if the server listens and the user’s source host allows it |
| Typical setting | Database on the same server as PHP | Containers, separate database clusters, managed databases |
| First experiment | Try 127.0.0.1 with the right port | Try localhost, or test from the web server itself |
Family two: the database server is down or starved
If your errors are cannot-connect numbers, or the standalone test and the panel database tool both fail, suspect the server. On a shared plan you cannot fix this yourself, but you can confirm it and hand your host precise evidence. On a VPS or dedicated server you can check four things in minutes:
$ sudo systemctl status mysql
$ df -h
$ df -i
$ free -m
$ sudo dmesg | grep -i -E "out of memory|killed process"
The service name varies: mysql, mysqld or mariadb, depending on the distribution and package. The status output says whether the server is running. The df -h command shows disk space, and df -i shows inodes, the file-count budget, which can run out while space remains. The free -m command shows memory and swap. The last line searches kernel messages for the out-of-memory killer, which on small servers tends to pick the largest process, often the database. A server that dies every few days with nothing in its own log is the classic sign.
Memory trouble has a recognisable cause: a configuration that lets the database claim more memory than the machine has once PHP workers, caches and the operating system are counted. Every open connection also uses memory, so raising max_connections to cure “too many connections” can trade one outage for another. A full disk stops the server writing and can leave tables damaged, which leads into the corrupted tables family. Common culprits are binary logs that were never rotated, backups stored on the same disk and oversized logs.
Read why it stopped before you restart it, because the database’s own error log usually says. After a crash a restart triggers crash recovery, which can take a while on a big database, so watch the log and do not kill the process during it. If the server is up but refusing connections, an administrator can see the connection picture:
SHOW VARIABLES LIKE 'max_connections';
SHOW STATUS LIKE 'Max_used_connections';
SHOW STATUS LIKE 'Threads_connected';
SHOW FULL PROCESSLIST;
If Threads_connected sits at max_connections, the server is saturated, and the process list shows what everyone is doing. Many identical slow queries point at a query problem. Many connections sleeping while PHP holds them point at a worker problem. MySQL keeps one spare connection for administrator accounts, so you can usually still log in locally when ordinary users are locked out. On managed database services, a failover or maintenance event can also cause a short burst of errors, so check the provider’s event log before blaming the web server.
Family three: host limits, traffic and query load
Host limits are the family textbooks skip and real sites meet constantly. On shared and many managed plans each account has ceilings: simultaneous database connections, entry processes, CPU time, memory and disk input and output. Cross one and the host refuses or kills work even though the database server is healthy for everyone else. From WordPress’s side it looks like an outage, except that it is intermittent and follows load. The tell-tale numbers are 1203 and 1226, and the tell-tale pattern is errors clustering around traffic peaks, backup windows, imports and scheduled tasks.
Every PHP request that touches the database holds a connection for as long as it runs. Duration matters, not page size. A query that takes ten seconds holds its slot for ten seconds, so a handful of slow pages can fill a small ceiling when many visitors arrive together. Picture the example store with around 800 products: if the shop page runs an expensive meta query and a promotional email sends a few hundred shoppers to uncached pages within minutes, the account’s connection limit can be exhausted without the site being large at all.
What to do about it:
- Look at the usage graphs. Most panels show CPU, memory, processes and sometimes connections per account. Compare the error times against them and ask the host for limit-hit logs.
- Stop wasteful traffic. Bots hammering search, login, cart or XML-RPC endpoints create uncached work. Rate limiting or a firewall in front of the site removes it.
- Move scheduled work. WP-Cron runs when pages load. Setting
define( 'DISABLE_WP_CRON', true );and triggering wp-cron.php from a real scheduled job gives you control over when heavy tasks run. Put backups and imports in quiet hours. - Find the expensive queries. The Query Monitor plugin lists the queries a page runs, how long each took and which plugin or theme issued it. It only helps while a page loads, so use it when the site is up, on the pages that were slow just before the failure.
If the limit is real and the site is simply bigger than its plan, no tuning fixes that. The honest options are lighter pages, a plan with higher limits or a different hosting model. Verify the limits in your provider’s current plan documentation, because they differ and change.

Family four: corrupted tables and WP_ALLOW_REPAIR
Table damage comes from interrupted writes: a crash, a power loss, a killed database process or a full disk. Older MyISAM tables are far more vulnerable than InnoDB, which has crash recovery built in. First find out which engine your tables use, replacing the example name with your database:
SELECT table_name, engine FROM information_schema.tables WHERE table_schema = 'example_wpdb';
Before any repair, copy the database as it is, because a repair can discard rows it cannot read. With WP-CLI, the DB commands read wp-config.php and call the MySQL client tools, so they usually work even when WordPress itself cannot load, provided those tools are installed:
$ wp db export before-repair.sql
$ wp db check
If the export fails on one table, that table is a prime suspect. The check command reports a status for every table.
WordPress also has a built-in repair page. Add this line to wp-config.php above the comment that tells you to stop editing, then open the wp-admin/maint/repair.php path on your site:
define( 'WP_ALLOW_REPAIR', true );
The page offers a repair and a repair-and-optimize option. It checks each WordPress table and attempts a repair where needed. Three things matter. It needs a working connection, so it is useless for credential, host or server faults. It does not require a login, by design, because it exists for situations where you cannot log in. While the constant is set, anyone who finds the address can start it and load your database, so work quickly and delete the line as soon as you finish, even if the repair failed. And a table repair only works for storage engines that support it, MyISAM among them. InnoDB tables generally report that the engine does not support repair. That is not a WordPress fault. For InnoDB the route is crash recovery (restart the server and read its log), then a dump and reimport into a clean database, or a restore.
WP-CLI offers the same operations as wp db repair and wp db optimize. Server administrators also have a last resort for an InnoDB server that will not start: the innodb_force_recovery setting, which starts the server in a limited mode so you can dump data. It runs from 1 to 6, higher values risk making damage permanent, and it exists to export data for a rebuild, never to run a live site. Leave it to an experienced administrator or your host.
After a repair, verify rather than assume. Load the front end, log in, open recent posts, and for a store compare the count of recent orders with what your payment provider shows. Optimising a large table can take time and add load, so do it off-peak.
A careful repair, in order
- Confirm the connection worksRun the standalone test. Repair needs a working connection.
- Copy the database firstExport it or snapshot the server before any rows are repaired.
- Check engines and tablesInnoDB and MyISAM take different routes.
- Run the repair page onceAdd WP_ALLOW_REPAIR, open the page, run it, read the output.
- Remove the constant at onceThe page has no login while the constant is set.
- Verify the dataCompare recent posts and orders, not just whether the site loads.
- Still broken: restoreMove to a backup restore, keeping your fresh copy.
Restoring from backup without making things worse
A restore is the right answer for one family only: lost or unrepairable data. For credential, host, limit and server faults it destroys recent work for no benefit. Before restoring, answer three questions. Is the data really lost, meaning a repair failed or tables are gone? How old is the newest backup, and what happened between its timestamp and now? And is the backup itself usable?
The gap is the real cost. For a blog it may be a comment or two. For a store, every order, customer, stock change and form entry since the backup is missing after a restore. Before you restore, export what you can, and list recent orders from your payment provider and from confirmation emails so you can reconcile them afterwards. Payment webhooks may keep failing while the site is down, so plan to look for orders that were paid but never recorded.
One paradox catches many people: backup plugins live inside wp-admin, and wp-admin needs the database. With the connection broken you cannot click restore. The way round it is manual. A backup set normally includes the database as a compressed SQL file, which you can fetch from the host’s file manager or from the remote storage the plugin used. Import it with the host’s database tool or WP-CLI, and check the plugin’s documentation for how its files are named. Never keep the only copy of your backups on the same server as the site, because the failure that takes the site down may take the backups with it.
$ wp db export before-restore.sql
$ wp db import backup-database.sql
The first line preserves the current state and the second loads the backup. Dumps from the usual tools drop and recreate each table, so an import replaces what is there, which is exactly why the export comes first. A compressed dump must be unpacked before WP-CLI will import it. If you can, restore to a staging copy first to confirm the backup shows the data you expect.
After the import, check the site address options, clear every cache layer, log in, view recent content and run a test checkout. If your server or managed database has binary logging or point-in-time recovery switched on, you may be able to restore to just before the failure instead of to last night’s backup. Ask your provider whether that exists for you, because it is not something to assume.

What to ask your host, and what to bring
When the evidence points at the server, the limits or the network, you need your host, and the quality of your first message decides how long this takes. A ticket that says “my site shows a database error” earns a generic reply. A ticket with a time, an error number and a question earns a specific answer.
Bring this evidence:
- The time the error first appeared, with your time zone.
- The numeric error code from the debug log or the standalone test.
- Whether wp-admin and any other sites on the account fail the same way.
- What changed beforehand: updates, migrations, password changes, traffic events.
- The domain and database name, but never the password. Support does not need it, and tickets and chat logs are stored.
Then ask direct questions:
- Was the database server restarted, failed over or under maintenance at that time?
- Did my account hit a connection, CPU, memory, process or input and output limit, and can you show the limit log?
- What is the maximum number of database connections my account may hold?
- What are the correct database host, port and socket for this account now, and did they change?
- Did the account reach a disk or inode quota, or was it flagged or suspended?
- What does the database error log say around that time?
- Which PHP and database versions run now, and did either change recently?
- What backups exist, how recent is the newest, and can a database snapshot be restored to a separate location for me to inspect first?
On an unmanaged server the same questions go to whoever runs it, or to your own logs. Judge any reply by its specificity. “It is fixed” tells you nothing. “The server ran out of memory and was restarted at this time, and your account was at its connection limit” tells you the family, tells you whether it will repeat, and tells you what to change. Ask what stops a recurrence, and note it if the host cannot say.
During the outage: status pages, maintenance and communication
While you diagnose, visitors see a bare error page. Decide quickly what they should see instead. WordPress has a supported hook for this: if a file named db-error.php exists in wp-content, WordPress shows it instead of its own message when the database connection fails. It runs without the database, so it must be static. This version tells browsers and search engines that the problem is temporary:
<?php
http_response_code( 503 );
header( 'Retry-After: 300' );
header( 'Content-Type: text/html; charset=utf-8' );
?>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Back shortly</title></head>
<body>
<h1>We are fixing a technical problem</h1>
<p>The site will be back shortly. Please try again in a few minutes.</p>
</body>
</html>
A 503 status says “temporary”, and short outages with that status are generally tolerated by search engines. A long one is a different matter, because pages that keep failing for days can eventually drop out of results, so do not let an unresolved outage sit unattended. Most maintenance-mode plugins read their settings from the database, so they cannot help when it is down. A host or server level maintenance page, or db-error.php, works without it.
Communicate on the channels that do not depend on the site. Post on social accounts and send a short email if the outage is long. Pause anything that pushes traffic into a failing site: ads, email campaigns and scheduled sends. For a store, expect payment webhooks to fail during the outage and reconcile orders afterwards.
Some visitors may still see content. A page cache that serves stored files, or a CDN configured to serve stale copies when the origin errors, can keep anonymous pages visible. Check how yours behaves before you need it, and never assume. Also tell your own team or clients what is happening and when you will next update them, because a short honest message prevents a flood of duplicate reports.
Finally, keep a plain log of what you changed and when. Under stress it is easy to try three fixes at once and forget which one worked.
A suggested rhythm for an outage
Preventing a repeat: caching, monitoring and backups
Recurrence usually means pressure the site cannot absorb, so prevention is mostly about asking the database for less, noticing trouble sooner and being able to recover fast.
Cache pages. A page cache stores finished HTML so repeat visitors never run WordPress or touch the database. Cache plugins load a drop-in file very early, before WordPress opens its database connection, so a page cache may keep serving stored pages to anonymous visitors during a database failure. That depends on the plugin and on how long cached pages live, so verify it instead of assuming. Logged-in users, carts, checkout and wp-admin always need the database. An object cache such as Redis or Memcached cuts repeated queries, but it loads after the connection exists, so it reduces load and does not replace the database during an outage.
Trim query load. Review plugins that run heavy queries on every page, and use Query Monitor on the slowest pages while the site is healthy. Fixing one plugin often does more for connection counts than any server setting.
Monitor the right thing. An uptime check that only looks at a cached home page can report healthy while the database is down. Use a keyword check on a page that really needs the database, and send alerts to a channel you watch. On a server you control, also watch disk space, memory and the number of connections against the maximum, with alerts well before they reach the limit.
Back up for recovery. Back up the database more often than the files, keep at least one copy off the server, and restore into staging on a schedule. A backup you have never restored is a hope, not a plan.
Change carefully. Test PHP and database version changes and plugin updates on staging first. Make sure deploy and migration tools never overwrite wp-config.php with another environment’s copy, and keep the database host, port and credentials in a password manager.
How much of a request needs the database
How to read this: each row is one option, and its dot shows where it sits between Needs no database and Needs it on every request. Placement is an editorial judgement, not a measurement.
- 1CDN-cached pageCan be served while the origin is down, if the CDN is set up to do so.
- 2Page cache hitStored HTML served before WordPress connects, depending on the plugin.
- 3Object-cached pageFewer queries, but WordPress still connects first.
- 4Uncached WordPress pageRuns many queries and holds a connection while it does.
- 5Cart, checkout and wp-adminPersonal and always live, so never served from a shared cache.
Checklist
- Load the home page, a deep URL and wp-admin in a private window, ideally from a second network.
- Compare the wp-admin message with the front-end message.
- Check the host status page and any notice in your email or control panel.
- Check whether other sites on the same account or server fail too.
- Download wp-config.php and take a snapshot or on-demand backup before changing anything.
- Turn on WP_DEBUG and WP_DEBUG_LOG with display off, and read the numeric error code.
- Run the standalone connection test, then delete it immediately.
- Verify DB_NAME, DB_USER, DB_PASSWORD and DB_HOST against the database section of the control panel.
- Try the other form of DB_HOST, localhost or 127.0.0.1, and confirm the port, one change at a time.
- On a server you control, check service status, disk space, inodes, memory and the out-of-memory killer.
- Compare error times with traffic, cron jobs, backups and the account’s resource graphs.
- Export the database before any repair, run the repair page once and remove WP_ALLOW_REPAIR.
- Verify posts and recent orders after any repair or restore, then clear every cache layer.
- Remove debug settings, delete debug.log and delete any test files.
- Put up a 503 db-error.php page if the outage will last, and pause campaigns and scheduled sends.
- Add an uptime monitor with a keyword check and schedule a restore test.
Read this next
About this guide. This is general guidance written by WPresident Editorial from documentation and widely used practice. WPresident has not benchmarked the products or methods described. Interfaces and plan limits change, so check the vendor’s current documentation before you act. Not legal, tax or financial advice. See our editorial policy.
Frequently asked questions
Does this error mean my site was hacked?
Usually not. Most cases are a changed password, a stopped server, a limit or a damaged table. Treat it as suspicious if it appears alongside unfamiliar files, a wp-config.php you did not edit or credentials that changed without anyone changing them. In that case follow an incident process, not just a connection fix.
Will I lose my content?
Normally no. Posts, pages and settings live in the database, and the error means WordPress cannot reach it, not that it was deleted. Content is at risk only when the cause is damage, such as a crash or a full disk, which is why you copy the database before any repair or restore.
Can a plugin or theme cause it?
Not directly through PHP bugs, because the connection is made before plugins and themes load. Indirectly, yes. A plugin that runs heavy queries or imports can exhaust connections, a security or cache plugin can rewrite wp-config.php, and a backup job can overload a small plan. If the error began after a plugin change, check wp-config.php and the load graphs, not only the plugin list.
Why does the error come and go?
Intermittent errors usually mean a ceiling being touched: a per-account connection limit, a server at its maximum connections, or memory pressure that kills and restarts the database. Compare the error times with traffic, scheduled tasks and backups, and ask your host for limit logs. Wrong credentials and wrong hostnames almost never fail intermittently, so changing them rarely helps.
Should I reset the database password?
Only when the evidence says access denied and you cannot find the cause in wp-config.php. A reset does nothing for cannot-connect errors, and it can break other tools that share the login. If you do reset it, change the control panel and wp-config.php in the same minute, use a long password without awkward characters and run the standalone test afterwards.
Is it safe to leave WP_ALLOW_REPAIR on?
No. The repair page needs no login while the constant is set, so anyone who finds the address can start repair or optimise operations and load your database. Add the line only for the minutes you need it, run the repair once and delete the line, even when the repair failed. Open wp-config.php afterwards to be sure it is gone.
Does the repair page fix InnoDB tables?
Generally not, because the table repair statement works for MyISAM and a few other engines but not for InnoDB. For InnoDB the usual routes are letting the server finish crash recovery, exporting and reimporting the data into a clean database, or restoring a backup. A server that cannot start at all is a job for your host or an experienced administrator.
Can I fix it with only FTP and no shell access?
For credential and host problems, yes. Edit wp-config.php, use the database tool in your control panel and run the standalone test script. WP_ALLOW_REPAIR also needs only a file edit. Server-down, limit and disk problems need your host, because they sit below what your account can touch, so contact support with the evidence you gathered. Download wp-config.php before editing it.
The site now shows the WordPress installation screen. What should I do?
Stop, and do not run the installer. On an established site it usually means WordPress connected but found no tables with the expected prefix, so the table prefix or database name in wp-config.php points at the wrong or an empty database. Compare them with the tables in your database tool. Installing can create a second, empty set of tables and makes the situation harder to untangle.
How is this different from the critical error or the white screen?
Those are PHP failures that happen after the connection succeeds, typically in a plugin, a theme or a memory limit, and they have their own diagnosis. The connection error happens first, before plugins and themes load. If wp-admin shows the critical error notice or a blank page, the connection works and you should debug PHP. If both show the connection error, stay with this guide.



