"Error establishing a database connection" means WordPress tried to open a connection to its MySQL or MariaDB database and failed, so it cannot build any page. The cause is one of six things: wrong credentials in wp-config.php, a database server that is down, a database user without the right permissions, damaged tables, a server that is refusing connections because it is overloaded, or a wp-config.php file that someone has changed. Your posts, pages and orders are almost always still in the database. The fix is to work through those causes in order, because each check rules out the next.
What "error establishing a database connection" actually tells you
Every WordPress page starts by connecting to the database with four values from wp-config.php: DB_NAME, DB_USER, DB_PASSWORD and DB_HOST. If that connection fails, WordPress stops and prints this message. It also sends an HTTP 500 status, so search engines treat it as a temporary server error rather than indexing the message as your content.
What visitors see is deliberately vague. WordPress has more specific messages, and there is a simple way to read them: load /wp-admin/ instead of the home page. In the admin, WordPress prints the detailed reason rather than the one-line version. (If a custom db-error.php page is installed, it replaces both, so rename it while you diagnose.) The detailed messages are:
- "Error establishing a database connection" with a note that either the username and password are incorrect or the database server at your host could not be reached. The login itself failed.
- "Cannot select database". The login worked, so the username and password are fine, but the database named in
DB_NAMEdoes not exist or this user has no permission to use it. - "Error reconnecting to the database". The connection worked earlier and was then lost, which points at a server that is down or under heavy load.
- "One or more database tables are unavailable. The database may need to be repaired." The connection and database are fine, but some WordPress tables are missing or unreadable.
That distinction alone halves the search. The steps below confirm it from the server side, which also gives you evidence to put in front of your host.
How to fix error establishing a database connection, in the order a developer checks
Before changing anything, take a copy of wp-config.php. If you have shell access, also confirm WP-CLI is available. Several WP-CLI commands still work while the site is down, because they read wp-config.php without loading the rest of WordPress. wp config get and wp db check are two of them.
1. Read the credentials WordPress is actually using
# Print the four connection settings from wp-config.php
wp config get DB_NAME
wp config get DB_USER
wp config get DB_HOST
# Avoid printing the password on a shared screen or in a ticket
Without WP-CLI, open wp-config.php over SFTP or the host's file manager and find the four define() lines. Compare them with the database name, user and host shown in your hosting control panel. Common mismatches:
- A recent migration. The files moved, but wp-config.php still points at the old host's database name or user. Many hosts prefix both with your account name, such as
account_wpdb, and the prefix changes between accounts. - A password reset in the control panel that nobody copied into wp-config.php.
- The wrong DB_HOST. On many servers it is
localhost. On others the database runs on a separate host, a non-standard port or a socket. WordPress accepts all of these forms, as the official wp-config.php reference documents:
define( 'DB_HOST', 'localhost' ); // default
define( 'DB_HOST', '127.0.0.1:3307' ); // custom port
define( 'DB_HOST', 'mysql.example.com:3307' ); // remote host and port
define( 'DB_HOST', 'localhost:/var/run/mysqld/mysqld.sock' ); // Unix socket
Use the exact value your host gives you. A stray space or curly quote pasted from an email also breaks the connection, so retype the line rather than pasting it if in doubt.
2. Test the login outside WordPress
Now try the same credentials directly. This separates "WordPress has the wrong details" from "the database will not accept anyone".
# Try to log in with the wp-config.php values (you will be prompted for the password)
mysql -h localhost -u DB_USER_HERE -p DB_NAME_HERE
# For a custom port add -P 3307; for a socket use --socket=/path/to/mysqld.sock
# Is the database server running at all?
mysqladmin -h localhost ping
# On newer MariaDB the tool is called mariadb-admin; mysqladmin is usually kept as an alias
The ping result is more useful than it looks. It returns success whenever the server is running, even if it refuses your login with "Access denied". So if ping succeeds and the mysql login fails, the server is up and the problem is the username, password or host. If ping fails, the database server itself is down or unreachable, and on shared or managed hosting that is the host's job to fix. Tell them the time it started and that a direct connection from the server also fails. That moves you past the first-line script.
3. Check the user's permissions on the database
If the login works but WordPress still fails, or you saw "Cannot select database", the user may exist without being granted access to this particular database. That happens after a database is recreated or restored under a new name. Log in with the WordPress user and ask MySQL what it is allowed to do:
-- Run inside the mysql client, logged in as the WordPress database user
SHOW GRANTS FOR CURRENT_USER();
You should see a grant on the WordPress database, for example ON `account_wpdb`.*. If it is missing, add the user to the database in your control panel, usually under MySQL Databases with "All privileges", or ask your host to. On your own server, grant it as a root database user, and limit it to the one database rather than everything.
4. Check for damaged tables
If the credentials and permissions are right and the site still fails, or the error only appears on some pages or only in wp-admin, look at the tables themselves. With WP-CLI:
# Back up first. Repair can lose data on a badly damaged table.
wp db export ~/backup-before-repair.sql
# Check every table using the credentials in wp-config.php
wp db check
# Only if the check reports problems
wp db repair
Without shell access, WordPress has a built-in repair screen. Add this line to wp-config.php, above the "stop editing" comment, then visit /wp-admin/maint/repair.php:
define( 'WP_ALLOW_REPAIR', true );
The repair page does not require a login, because a site with a broken database usually cannot log anyone in. Anyone who knows the address can run it while that line is present. Remove the line as soon as you are finished.
One thing most guides leave out: according to the MySQL manual on REPAIR TABLE, it works on MyISAM, ARCHIVE and CSV tables. InnoDB is the default storage engine in current MySQL and MariaDB, so most WordPress tables on a modern server are InnoDB, and repair does not cover them. If a check flags InnoDB tables, or repair replies that the storage engine does not support it, the realistic fix is restoring those tables from a backup, and on a managed host it is a conversation with their database team. This is why a tested off-site backup matters more than any repair tool.
5. Make sure the core files are intact
Occasionally a failed update or a bad upload leaves WordPress core files half-written. WP-CLI can compare every core file with the official checksums from WordPress.org, and it does this without loading WordPress, so it works while the site is down:
# List any core file that differs from the official copy for your version
wp core verify-checksums
Modified core files are a reason to look further, which leads to the last cause.
6. Check whether wp-config.php has been changed by someone else
If the credentials in wp-config.php are suddenly different from the ones you set, and nobody on your team changed them, treat it as a security incident rather than a typo. wp-config.php is a favorite hiding place for malicious code because it loads on every request. In one cleanup we handled, the malware had hidden a "repair" routine inside the configuration file that rebuilt the rest of the infection whenever part of it was removed. Earlier cleanups had missed it, which is why they never stuck.
Signs to look for: code above the opening database settings, long encoded strings, include or require lines pointing at unfamiliar files, and a modification date that matches no work you know of. Compare the file with a backup from before the problem. If you find anything you cannot explain, stop editing and get a proper investigation, because whoever changed the file probably still has a way in.
When the error comes and goes: too many connections and resource limits
The hardest version of this problem is the one that fixes itself. The site shows the error for a few minutes, recovers, then fails again tomorrow. The credentials cannot be wrong, because they work most of the time. This is the case the top search results cover least, and it is usually a capacity problem.
A MySQL server accepts a limited number of simultaneous connections, set by its max_connections variable, as the MySQL documentation on too many connections explains. When every slot is in use, new connections are refused, and WordPress reports that refusal as "error establishing a database connection". On shared hosting there is often a second, lower limit per database user or per account, so your site can hit its ceiling even while the server has room.
What fills the connection slots
- Uncached traffic. Every page that is not served from a page cache opens a database connection. Search results, logged-in users, WooCommerce cart and checkout, and anything with a query string all bypass most caches.
- Bots. Aggressive crawlers, login brute-forcing against wp-login.php and xmlrpc.php, and scrapers hammering search can generate far more uncached requests than real visitors do.
- Slow queries. A connection is held for as long as its queries run. One slow report or an unindexed plugin query, multiplied by concurrent visitors, ties up the pool.
- Background work. Backups, imports and scheduled tasks firing at the same time as a traffic peak.
- Malware. Infected sites often run spam or attack code on every request.
That last one is more common than people expect. In a recent malware cleanup case study, a business site kept failing with "508 Resource Limit Is Reached" errors after a host move, and the host's scanner had removed one malicious plugin and called it done. We found eleven malicious plugin folders and twelve tampered files. On shared hosting, resource-limit errors and database connection errors are often two symptoms of the same pressure, so when either appears without an obvious traffic reason, check the site for infection before buying a bigger plan.
How to confirm it
If you have database access, these read-only queries show whether you are hitting the limit:
-- The configured ceiling
SHOW VARIABLES LIKE 'max_connections';
-- The highest number of simultaneous connections since the server started
SHOW GLOBAL STATUS LIKE 'Max_used_connections';
-- Connections open right now
SHOW GLOBAL STATUS LIKE 'Threads_connected';
-- Connections refused because max_connections was reached
SHOW GLOBAL STATUS LIKE 'Connection_errors_max_connections';
-- What each connection is doing (needs the PROCESS privilege to see other users)
SHOW FULL PROCESSLIST;
If Max_used_connections equals or sits just above max_connections, the server has been full. MySQL keeps one extra slot for administrative accounts, which is why an admin can still log in to look while WordPress is being refused. A non-zero Connection_errors_max_connections confirms refusals happened. A process list full of identical long-running queries points at the query, not the traffic.
Then line up the times with the web server access log. A quick count of the busiest IP addresses often makes the cause obvious:
# Top 20 client IPs in the current access log (adjust the path for your server)
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20
What fixes it
- Serve more pages from cache so fewer requests touch the database at all.
- Block or rate-limit abusive bots at the firewall or CDN, and protect wp-login.php and xmlrpc.php.
- Fix the slow query you found in the process list, usually a plugin feature that needs an index or a cache.
- Move heavy jobs off peak, such as backups and imports.
- Raise the limit last. A higher
max_connectionson a server without the memory to back it trades a connection error for a crashed database. On shared hosting, ask what your per-user limit is before upgrading.
What to tell your host
Host support works best with specifics. A ticket like this gets past the scripted replies:
- The exact times the error appeared, with your time zone.
- That the credentials in wp-config.php match the control panel, and a direct login from the server with the same user does or does not work.
- Whether
mysqladmin pingsucceeded. - For intermittent errors: ask whether the database server or your account hit a connection or process limit at those times, and what the per-user connection limit is on your plan.
- Whether any other sites on the same database server were affected.
If the host says everything is fine on their side and you have ruled out credentials, permissions and tables, the remaining suspects are load from your own site and a compromise. Both need someone to read logs, not restart services.
Preventing the database connection error from coming back
- Keep wp-config.php under change control. Know what it should contain, protect it with tight file permissions, and treat unexplained edits as a security event.
- Update credentials in one place. When you rotate a database password, change it in the control panel and wp-config.php together, then test immediately.
- Keep tested, off-site backups. A backup you have never restored is a hope. For InnoDB tables, a restore is usually the only real repair.
- Monitor uptime so you hear about the error from an alert rather than from a customer.
- Add a friendly error page. If a file called
db-error.phpexists in wp-content, WordPress shows it instead of the default message. Keep it as plain HTML with no database calls, and send a 500 status from it as WordPress does, so search engines do not index the page:
<?php
// wp-content/db-error.php: shown when WordPress cannot reach the database
http_response_code( 500 );
header( 'Retry-After: 300' );
?>
<!doctype html>
<title>Back shortly</title>
<p>We are fixing a technical problem. Please try again in a few minutes.</p>
A maintenance plan covers the backups, uptime monitoring and security monitoring in that list, which is most of what prevents a repeat.
If you have worked through the checks and the cause is still unclear, or wp-config.php shows signs of tampering, our WordPress site rescue service starts with a $300 written diagnosis and then a fixed price for the repair, usually started the same or next working day.
Common questions
Have I lost my posts and orders?
Almost certainly not. The error means WordPress cannot reach the database, not that the database is gone. Once the connection is restored, the content is where it was. The exception is genuinely corrupted tables with no backup, which is rare and is why you export the database before running any repair.
Why does error establishing a database connection come and go?
Intermittent errors usually mean the database server or your hosting account is running out of connections or resources at busy moments. Credentials do not change from minute to minute. Compare the times of the errors with your traffic, bot activity and scheduled jobs, and check Max_used_connections against max_connections.
Can a plugin cause this error?
Not directly by breaking the login, because the connection happens before plugins load. A plugin can contribute indirectly, by running slow queries that hold connections open under load until the server refuses new ones.
Is my site hacked if I see this error?
Usually not. Most cases are credentials, a server outage or load. It becomes a security question when wp-config.php contains values or code nobody on your team put there, or when the load turns out to come from malicious code running on your own site.
Why does wp-admin show a different database message from the front end?
By design. On the public site WordPress shows only the short message, so it reveals nothing useful to strangers. In wp-admin it shows the detailed reason, such as "Cannot select database" or "One or more database tables are unavailable". That detailed message tells you whether the login failed or whether the login worked and something after it did not, which is the first fork in the diagnosis.
Should I just restore a backup?
Only after you know the cause. Restoring files does not help if the database password changed, and restoring the database does not help if the server is down. If wp-config.php was tampered with, a restore can bring back the same backdoor. Diagnose first, then restore the specific thing that is broken.
Next step
If your site is down right now and you would rather have a senior developer find the cause, our WordPress site rescue service starts with a $300 written diagnosis and a fixed price for the fix. For anything longer term, you can start a project and we will come back with a written scope.
Want a senior developer to look at your site?
Tell us what you need. You get a written scope and a fixed price, usually within one business day.


