WordPress Database Connection Error: Fix It Fast
Check wp-config.php credentials first — most WordPress database errors come from bad login details, a stopped MySQL server, or crashed tables..
20+ years shipping production backend systems. Notes here come from systems that actually shipped.
- ✓Access to your hosting control panel and SFTP or file manager
- ✓Basic comfort editing a PHP config file and running backups
- ✓Know your hosting plan's database limits
- WordPress shows this when PHP runs but the MySQL connection fails — start with wp-config.php credentials
- Confirm MySQL is alive with mysqladmin ping before touching any tables
- Repair crashed tables via repair.php, then remove the constant right away
- Peak-hour-only errors mean max_connections or plan limits, not bad config
- After any fix, verify the homepage, wp-admin, and one write action before closing
Think of WordPress as a restaurant where the kitchen is the database. The dining room (your files) looks perfect, but if the phone line to the kitchen is cut, no food comes out and every customer gets the same apology. This error is that apology. The fix is checking the phone number (credentials), seeing if the kitchen is open (MySQL server), or fixing a messy recipe book (corrupted tables).
You open your site in the morning and instead of your homepage there's a single stark sentence: Error establishing a database connection. No layout, no styling, no admin bar. Every page shows the same thing, and your stomach drops because the site looks completely gone.
It's not gone. WordPress is telling you something specific: PHP runs fine, your files are intact, but the MySQL connection failed. Posts, pages, users, and settings all live in the database, so without that connection WordPress can't render a single page. The good news is the message narrows the problem to four suspects — wrong credentials in wp-config.php, a stopped MySQL server, crashed tables, or hosting limits.
This guide walks you through those four in the order you're most likely to hit them. You'll verify credentials without guessing, check whether MySQL is actually alive, repair crashed tables safely, and recognize when a cheap hosting plan is the real bottleneck. By the end you'll have a repeatable checklist that turns this scary message into a 15-minute fix.
What Error Establishing a Database Connection Means
Every WordPress page load opens a MySQL connection using four values from wp-config.php: DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST. If any of them is wrong, or the server refuses the connection, WordPress gives up and prints Error establishing a database connection. It prints this instead of a stack trace on purpose — database details are sensitive, so the public message stays vague while the real reason goes to the PHP error log.
The connection happens in wpdb, the database class in wp-includes/wp-db.php. It calls mysqli with your credentials during core load, before themes or most plugins run. That's why the whole site — frontend, admin, feeds — fails identically. A broken plugin can't cause this message; plugins load after the connection is established.
Your first instinct should be reading, not restarting. Open wp-config.php, note the four constants, and check the PHP error log for the matching Access denied or Unknown database error. Those two steps split the problem in half: access-denied means credentials, connection-refused means the server. Knowing which half you're in saves you from repairing tables that were never broken. On shared hosting, the panel's database status page answers the server half in seconds.
Verify wp-config.php Credentials and DB_HOST
Most of these errors trace back to wp-config.php. Migrations, host moves, staging pushes, and password rotations all change database credentials, and one stale value breaks every page. Open the file over SFTP or your host's file manager and find the four lines starting with define('DB_. Compare each against the database section of your hosting panel — database name, username, host, and password — exactly as shown there.
Passwords cause the most grief. Pasting from a password manager can add a trailing space, and some editors convert straight quotes to smart quotes, which silently breaks the string. If there's any doubt, re-type the password by hand between the existing quotes. Also confirm the database user is actually assigned to the database with full privileges — on cPanel hosts these are separate steps, and a user with no grants gets access-denied just like a wrong password.
DB_HOST deserves special attention. Localhost is right when MySQL runs on the same machine, but many shared and managed hosts use a separate database server like mysql123.hosting.com or a socket path. Copy the host value straight from your panel's documentation. After saving, re-download the file to confirm the edit uploaded, then hard-refresh the site.
Check Whether the MySQL Server Is Alive
If credentials check out, verify MySQL itself. On a VPS, run mysqladmin with your WordPress credentials and the ping command — an alive response means the server accepts connections. Then try listing tables in the WordPress database. If ping works but the table list fails with access-denied, you've proven it's a credentials problem, not a server problem.
If ping fails, check whether mysqld is running with your service manager, and look at disk space — a full disk stops MySQL from accepting writes and can mimic a total outage. Read the last 50 lines of the MySQL error log before restarting; it usually names the cause, like an out-of-memory kill or a corrupted page. Restarting without reading the log often just resets the countdown to the next crash.
On shared hosting you can't restart MySQL yourself, so check the host's status page and open a ticket with your error-log lines attached. Include the exact time the error started and whether phpMyAdmin in the panel still works — that tells support whether it's your database user or the whole server. Keep a note of the exact commands and outputs; support clears ticket queues faster when log excerpts arrive with the first message. If the panel offers a database check tool, run it only after noting the current error text for comparison.
Repair Corrupted Tables With WP_ALLOW_REPAIR
When credentials work and MySQL runs but WordPress still fails, suspect crashed tables. This follows hard power cuts, disks filling mid-write, or a killed import. WordPress may partially load or fail on specific pages while others work, since only some tables are damaged.
The built-in fix is the repair page. Add the WP_ALLOW_REPAIR constant to wp-config.php, visit /wp-admin/maint/repair.php, and run Repair Database. It issues REPAIR TABLE against each WordPress table and reports results per table. For a surgical fix you can repair a single table from the MySQL shell instead, which locks less on a busy site.
Treat repair as a last resort with a backup taken first. Repairing a badly crashed MyISAM table can discard rows it can't reconcile. After the repair, remove the constant from wp-config.php immediately — the repair URL has no authentication, and leaving it open invites anyone to trigger table locks. Then verify wp-admin, several posts, and one write action like a new draft before calling it done. If the repair page reports errors it can't fix, stop and restore from backup rather than repeating the repair — repeated runs on a dying disk can turn recoverable rows into lost ones.
Spot Hosting Limits and Max Connections Caps
If the error appears only during traffic spikes, backups, or import jobs, you're hitting limits rather than breakage. Small hosting plans cap simultaneous MySQL connections, and WordPress plus backup plugins plus WP-Cron can exhaust them together. The site works at 3 AM and fails at 8 PM — that's the signature.
Confirm it by catching the failure in the act. Run SHOW FULL PROCESSLIST during the outage and compare the connection count against max_connections. If the list is full of sleeping WordPress connections, the pool is saturated. Check whether backups, cron, or a traffic surge coincide with the failures in your access logs.
The fixes stack. Page caching cuts database connections dramatically because cached pages never query MySQL. Move backups and heavy cron jobs to off-peak hours so they don't pile onto evening traffic. Ask your host about raising max_connections, and if you're on the cheapest shared tier with a busy store, accept that an upgrade or a move to a VPS is the honest fix — no plugin overcomes a hard connection cap. As a stopgap, a maintenance plugin that queues logins during peaks can smooth spikes while you plan the upgrade. Record peak connection counts for a week; the numbers justify the upgrade request to whoever holds the budget.
Restore From Backup When Repairs Fail
When nothing above resolves it, restore from backup instead of experimenting further. Export what's there now for forensics, then restore the last known-good backup through your host's tool or WP-CLI. Restoring beats hours of trial repairs that risk making a damaged database worse.
WP-CLI makes this fast. Export the current state, download a backup copy off-server, then import the good backup and flush caches. After importing, update the site URL if the backup came from staging, and test the homepage, wp-admin login, and one transaction like a test order or comment.
Whatever fixed it, finish by preventing a repeat. Turn on automated daily backups with off-server copies, add a homepage check that alerts you when the database-error text appears, and write down what the cause was. The next time this message appears at midnight, that note turns panic into a checklist. Test restores quarterly on staging — a backup never restored is a hope, not a plan. Time the restore so you can quote a recovery window honestly, and store one copy off the host entirely. Document the database name, user, and host in your runbook so the next midnight page starts with answers. Record the last error timestamp too; support threads and post-mortems both start from knowing exactly when the failure began.
Midnight Password Rotation Broke Checkout for 74 Minutes
- Credential rotations must include every app config that uses the password, not just the database. Keep a checklist of consumers — WordPress, cron jobs, external dashboards — and verify each one after rotation.
- Don't restart the database before reading wp-config.php. A 30-second credential comparison would have turned a 74-minute outage into a 5-minute fix.
- Load secrets from environment variables so rotations touch one vault entry instead of scattered config files. Then add a homepage content check, not just a ping, so silent credential breaks page someone immediately.
| File | Command / Code | Purpose |
|---|---|---|
| wp-config.php | define( 'DB_NAME', 'shop_wp421' ); | Verify wp-config.php Credentials and DB_HOST |
| mysqladmin -h localhost -u shop_wpuser -p ping | Check Whether the MySQL Server Is Alive | |
| CHECK TABLE wp_posts, wp_postmeta, wp_options, wp_users; | Repair Corrupted Tables With WP_ALLOW_REPAIR | |
| wp db export /tmp/pre-fix-$(date +%F).sql | Restore From Backup When Repairs Fail |
Key takeaways
Common mistakes to avoid
5 patternsEditing wp-config.php and assuming the credentials are right
Leaving DB_HOST as localhost on managed hosting
Leaving WP_ALLOW_REPAIR enabled after fixing tables
Restarting MySQL before checking the real cause
Fixing the database with no backup in place
Interview Questions on This Topic
What does Error establishing a database connection actually mean?
Frequently Asked Questions
20+ years shipping production backend systems. Notes here come from systems that actually shipped.
That's WordPress. Mark it forged?
5 min read · try the examples if you haven't