Home › Web Platform › WordPress Database Connection Error: Fix It Fast
Beginner 5 min · September 23, 2026

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..

N
Naren Founder & Principal Engineer

20+ years shipping production backend systems. Notes here come from systems that actually shipped.

Follow
✓ Production
production tested
September 27, 2026
last updated
2,085
articles · all by Naren
Before you start⏱ 18 min
  • ✓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
 ● Production Incident 🔎 Debug Guide
⚡Quick Answer
  • 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
✦ Definition~90s read
What is WordPress Error Establishing a Database Connection?

Error establishing a database connection is the message WordPress shows when its PHP code can't open a MySQL connection. WordPress stores nearly everything in the database — posts, pages, comments, users, plugin settings, menus — while the filesystem holds themes, plugins, uploads, and core files.

★
Think of WordPress as a restaurant where the kitchen is the database.

Each page load connects with the credentials in wp-config.php, runs dozens of queries, and renders the result. Break the connection and nothing renders, which is why every URL shows the same plain message.

Four causes cover nearly all cases. Wrong credentials in wp-config.php after a migration or password change is the most common. A stopped or unreachable MySQL server comes next, caused by crashes, full disks, or memory kills. Crashed tables after power loss or killed writes cause partial or total failures.

Finally, hosting limits — max_connections caps or exhausted memory on shared plans — produce errors only under load.

The message is deliberately vague to avoid leaking database details to visitors. The specifics live in the PHP error log as Access denied or Connection refused lines. Reading those lines first is the whole trick: they tell you whether to fix credentials, revive the server, repair tables, or ease off resource limits.

Plain-English First

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.

📊 Production Insight
In production, tail the PHP error log first. Access denied for user tells you it's credentials; Connection refused tells you MySQL is down. That one line picks your next step.
🎯 Key Takeaway
The message means wpdb couldn't connect — read wp-config.php and the PHP error log before changing anything.

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.

wp-config.phpPHP
1
2
3
4
5
6
7
8
// wp-config.php — the four values WordPress uses to connect
define( 'DB_NAME', 'shop_wp421' );
define( 'DB_USER', 'shop_wpuser' );
define( 'DB_PASSWORD', 're-type-this-by-hand' );
define( 'DB_HOST', 'localhost' ); // or mysql123.hosting.com on shared hosts

// Optional: load the password from the environment instead of hardcoding it
// define( 'DB_PASSWORD', getenv( 'WP_DB_PASSWORD' ) );
📊 Production Insight
After any migration, diff wp-config.php against the new panel values before touching the server. Stale credentials cause more of these outages than actual database crashes.
🎯 Key Takeaway
Compare all four DB_ constants against your hosting panel and re-type the password by hand.

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.

BASH
1
2
3
4
5
6
7
8
9
10
11
# Are we reaching MySQL at all?
mysqladmin -h localhost -u shop_wpuser -p ping
# expected: mysqld is alive

# Can these credentials see the WordPress database?
mysql -h localhost -u shop_wpuser -p -e 'SHOW TABLES;' shop_wp421

# VPS only: is the service up, is disk full, what does the log say?
systemctl status mysqld --no-pager
sudo df -h /var/lib/mysql
sudo tail -n 50 /var/log/mysql/error.log
📊 Production Insight
Never restart MySQL before reading the error log. The log names the killer — OOM, full disk, crashed table — and restarting blind just schedules a repeat.
🎯 Key Takeaway
mysqladmin ping plus a manual login splits credential failures from server failures in seconds.

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.

SQL
1
2
3
4
5
-- Check which tables are actually crashed before repairing anything
CHECK TABLE wp_posts, wp_postmeta, wp_options, wp_users;

-- Repair one crashed table (faster and safer than repairing all)
REPAIR TABLE wp_posts;
⚠ Remove WP_ALLOW_REPAIR When Done
The repair page at /wp-admin/maint/repair.php has no login check. Add the constant, run the repair once, and delete the constant the same day.
📊 Production Insight
On a live store, repair the single crashed table from the MySQL shell at a quiet hour instead of running the whole repair page — fewer locks, less downtime.
🎯 Key Takeaway
Back up first, repair with repair.php or REPAIR TABLE, then remove the constant and verify the site.

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.

📊 Production Insight
Correlate outage times with backup and cron schedules first. A backup job moved from 8 PM to 3 AM has resolved more of these than any code change.
🎯 Key Takeaway
Peak-hours-only failures mean saturated connections — cache pages and stagger heavy jobs before upgrading.

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.

BASH
1
2
3
4
5
6
7
8
9
10
11
# Save the current (broken) state for forensics
wp db export /tmp/pre-fix-$(date +%F).sql

# Restore the last known-good backup
wp db import /tmp/good-backup.sql
wp cache flush
wp rewrite flush

# Sanity checks after restore
wp option get siteurl
wp post list --posts_per_page=3
📊 Production Insight
Always export the broken state before importing. Twice a broken import has been blamed on the backup when the real culprit was an import run against the wrong database name.
🎯 Key Takeaway
Restore the last good backup rather than experimenting on a damaged database — then automate backups.
● Production incidentPOST-MORTEMseverity: high

Midnight Password Rotation Broke Checkout for 74 Minutes

Symptom
At 00:42 the storefront and wp-admin both showed Error establishing a database connection on every page. Checkout was fully down through the 01:00-02:00 window, costing about 340 abandoned carts. Static assets and the host status page were fine, and MySQL responded to pings the whole time.
Assumption
The team assumed the database server had crashed because the error message sounds like a server problem. Two engineers spent an hour checking MySQL status, restarting services, and reading slow-query logs. Nobody looked at wp-config.php because no deploy had happened that day.
Root cause
The host's automated security rotation changed the database password at 00:40, but wp-config.php still held the old hardcoded password. Every WordPress request failed authentication — roughly 1,900 failed connections over 74 minutes — while MySQL itself stayed healthy. The team restarted mysqld twice, which did nothing because authentication, not availability, was broken.
Fix
They restored the correct password into wp-config.php from the secrets vault, reloaded the site in seconds, and added two safeguards: wp-config.php now loads DB_PASSWORD from an environment variable instead of a hardcoded string, and a 2-minute uptime check hits the homepage and alerts Slack on any database-error text. A later migration rehearsal verified the check fires correctly.
Key lesson
  • 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.
Production debug guideFive checks in order — credentials, server, tables, limits, safety net.5 entries
Symptom · 01
Error appeared right after a migration, host move, or password change
→
Fix
Open wp-config.php and read DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST. Log into your hosting panel's database section and compare each value exactly. Re-type the password by hand to remove hidden whitespace, save, and reload the site. If you edited over SFTP, re-download the file to confirm the upload landed.
Symptom · 02
You need to separate bad credentials from a dead server
→
Fix
Run mysqladmin -h your-host -u your-user -p ping. If it answers alive, credentials are the suspect — test them with mysql -u user -p -e 'SHOW TABLES;' dbname. If ping fails, check systemctl status mysqld (VPS) or your host's status page (shared hosting) and read the MySQL error log's last 50 lines before restarting anything.
Symptom · 03
Credentials test fine and MySQL is running, but WordPress still fails
→
Fix
Add define('WP_ALLOW_REPAIR', true); to wp-config.php, visit yoursite.com/wp-admin/maint/repair.php, and click Repair Database. When it finishes, delete that line from wp-config.php immediately — the page has no login protection. Then load wp-admin and a few posts to confirm everything renders.
Symptom · 04
Error strikes only during traffic spikes or backup windows
→
Fix
Connect with mysql -u root -p and run SHOW FULL PROCESSLIST; plus SHOW VARIABLES LIKE 'max_connections';. If the list is full of sleeping WordPress connections at peak hours, enable page caching, stagger backup and WP-Cron jobs away from peaks, and ask your host about raising max_connections or moving up a plan.
Symptom · 05
You're about to repair or restore and have no safety net yet
→
Fix
Before any REPAIR or import, export a full backup with wp db export /tmp/pre-fix.sql or your host's backup tool. After the fix, verify the homepage, wp-admin, and one write action like publishing a test draft. Confirm tonight's automated backup is still scheduled so you're never one crash away from data loss.
Database Connection Error Causes Compared
Root CauseHow to ConfirmFixPrevention
Wrong credentials in wp-config.phpError appears right after a migration or password change; host panel login worksCorrect DB_NAME, DB_USER, DB_PASSWORD, DB_HOST in wp-config.phpDocument credentials per environment; re-test after every migration
MySQL server down or unreachablemysqladmin ping fails; host status page shows an incidentRestart MySQL; fix disk-full or OOM cause firstMonitor mysqld with alerts on downtime and disk usage
Corrupted tables after a crashCHECK TABLE reports crashed status; repair page lists errorsRun REPAIR TABLE or repair.php, then remove the constantKeep InnoDB; schedule automatic backups; avoid killing mysqld
Hosting connection or resource limitsError only at peak traffic; SHOW PROCESSLIST hits max_connectionsRaise limits, cache pages, or upgrade the planCache aggressively and stagger WP-Cron and backup jobs
⚙ Quick Reference
4 commands from this guide
FileCommand / CodePurpose
wp-config.phpdefine( 'DB_NAME', 'shop_wp421' );Verify wp-config.php Credentials and DB_HOST
mysqladmin -h localhost -u shop_wpuser -p pingCheck 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).sqlRestore From Backup When Repairs Fail

Key takeaways

1
The error means PHP works but the MySQL connection failed
files are fine.
2
Check wp-config.php credentials first; they cause most cases after moves.
3
Verify MySQL is running and reachable before touching tables.
4
Repair crashed tables with repair.php, then remove the constant.
5
Peak-hours-only errors point at max_connections or plan limits.
6
Keep tested backups
never repair a database you can't restore.

Common mistakes to avoid

5 patterns
×

Editing wp-config.php and assuming the credentials are right

Symptom
The error persists after a credential change because of a pasted trailing space, a smart quote, or an upload that never finished. You keep chasing server problems that don't exist.
Fix
Open wp-config.php and compare DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST character by character against the database section of your hosting panel. Re-type the password instead of pasting it, then reload the site. If you edited the file over SFTP, confirm the upload actually completed.
×

Leaving DB_HOST as localhost on managed hosting

Symptom
WordPress can't reach MySQL even though the database, user, and password are all correct. The credentials work from the host's phpMyAdmin but not from WordPress.
Fix
Ask your host which value to use. Shared hosts often need a socket-style host or a specific port like db.example.com:3306. Set DB_HOST to exactly what the host documents, not what worked on your last host.
×

Leaving WP_ALLOW_REPAIR enabled after fixing tables

Symptom
The repair page stays publicly accessible. Bots hit it repeatedly, adding load, and a visitor can trigger table locks on a busy store during checkout hours.
Fix
Add the repair constant, run /wp-admin/maint/repair.php once, then remove the constant from wp-config.php immediately. Leaving it enabled lets anyone trigger a repair run.
×

Restarting MySQL before checking the real cause

Symptom
The site comes back for 20 minutes and dies again. The restart clears the connection pile-up but the plugin or traffic spike that caused it is still there.
Fix
Before restarting anything, run SHOW PROCESSLIST and check the error log timestamps. If connections are maxed, raise max_connections modestly or move heavy cron jobs off peak hours. Only then restart MySQL.
×

Fixing the database with no backup in place

Symptom
A REPAIR or restore attempt makes things worse — a crashed table loses rows or an import overwrites newer orders. With no backup, that data is gone for good.
Fix
Keep automated daily backups with a tested restore. After any database fix, verify wp-admin loads, test checkout or comment posting, and confirm the backup job ran that night.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
What does Error establishing a database connection actually mean?
Q02JUNIOR
Which four wp-config.php constants control the database connection?
Q03SENIOR
How do you tell a down MySQL server apart from bad credentials?
Q04SENIOR
What is the risk of WP_ALLOW_REPAIR and how do you handle it?
Q05SENIOR
The error appears only at peak traffic. How do you diagnose hosting limi...
Q01 of 05JUNIOR

What does Error establishing a database connection actually mean?

ANSWER
It means PHP and WordPress loaded fine, but the mysqli connection to MySQL failed. The usual causes are wrong credentials in wp-config.php, a stopped or unreachable MySQL server, corrupted tables, or the host hitting max_connections. Debugging starts at wp-config.php and moves outward to the server.
FAQ · 6 QUESTIONS

Frequently Asked Questions

01
Is this error the same as the white screen of death?
02
Can I repair tables without phpMyAdmin access?
03
Should DB_HOST always be localhost?
04
Can heavy traffic alone cause this error?
05
Will updating WordPress core fix it?
06
What order should I debug in?
N
Naren Founder & Principal Engineer

20+ years shipping production backend systems. Notes here come from systems that actually shipped.

Follow
✓ Verified
production tested
September 27, 2026
last updated
2,085
articles · all by Naren
🔥

That's WordPress. Mark it forged?

5 min read · try the examples if you haven't

1 / 5 · WordPress
Next
WordPress White Screen of Death — Isolate the Plugin
→