Your site was fine an hour ago. Now every page returns one line of plain text and nothing else.

Learning how to fix WordPress database errors comes down to knowing which layer broke: the connection, a query, or a corrupted table. Wrong credentials in wp-config.php, a crashed MySQL service, and a prefix mismatch after migration cause most of them.

Your content is still sitting in the database. WordPress just cannot reach it.

This guide covers the full repair path:

  • Reading debug.log to identify the exact fault
  • Fixing connection errors, missing tables, and corrupted InnoDB data
  • Restoring from backup when repair fails

What Is a WordPress Database Error?

A WordPress database error is a failure in the MySQL or MariaDB layer that stops WordPress from reading or writing site data. The break happens at one of three points: the connection, the query, or the table itself.

Every post, user, option, and setting lives in a relational database. The PHP files are only the delivery mechanism.

All communication runs through the wpdb class in wp-includes/class-wpdb.php. When wpdb cannot finish its work, you get a plain-text message instead of a page.

The database sits at the deepest layer of a site’s backend, so nothing above it survives a connection failure.

Error stringLayerUsual trigger
Error establishing a database connectionConnectionIncorrect database credentials, unavailable database server, or connection failure
One or more database tables are unavailableTableTable is missing, corrupted, or inaccessible
Table wp_posts doesn’t existTableTable-prefix mismatch, missing table, or incomplete database import
MySQL server has gone awayConnectionServer timeout, oversized packet, dropped connection, or server restart
Too many connectionsConnectionMySQL connection limit reached, often due to high traffic or long-lived connections

Scale explains why the same five strings keep appearing. W3Techs puts WordPress on roughly 43% of all websites and about 60% of the CMS market, so a narrow set of MySQL faults repeats across hundreds of millions of installs.

Have you seen the latest WordPress statistics?

Discover the latest WordPress statistics: market share, security trends, performance data, and revenue insights that shape the web.

Check Them Out →

Frontend Errors vs Admin-Only Errors

Both sides down: the connection failed. Credentials, DBHOST, or a stopped MySQL service.

Public pages broken, wp-admin loads: one table or one query on the visitor-facing side is damaged.

wp-admin broken, public pages fine: page cache is serving stale HTML while the database is already unreachable.

That third case fools people for hours. Visitors see a working site long after MySQL stopped answering.

Connection Failures vs Query Failures vs Table Corruption

Connection failures take down the entire site. Query failures break one feature. Corruption sits between the two and spreads if you keep writing to the damaged table.

None of this is a WordPress fatal error or a white screen of death, both of which originate in PHP rather than MySQL.

The tell is in the wording. PHP errors name a file and a line number. Database errors name a table, a query, or the connection.

What Causes WordPress Database Errors?

Six causes account for nearly every WordPress database error: wrong credentials in wp-config.php, a stopped MySQL service, corrupted tables, a table prefix mismatch, bloated autoloaded options, and a failed dbDelta() schema update during a plugin or core update.

Wrong credentials: Hostinger, GoDaddy, and WPBeginner all name incorrect values in wp-config.php as the single most common trigger, usually after a host migration or a password rotation.

Crashed or overloaded MySQL: shared hosting stacks dozens of accounts on one database server, so one noisy neighbour can exhaust maxuserconnections for everyone.

Table corruption: an unclean shutdown, a disk-full event, or an interrupted update leaves a half-written row that the storage engine refuses to trust.

Prefix mismatch: $tableprefix in wp-config.php no longer matches the prefix in the actual database, so WordPress asks for tables that were never named that way.

Autoload bloat: WP Engine recommends keeping total autoloaded data under 800 KB, and notes that excess autoload data is behind many performance failures, often surfacing as 502 gateway errors.

The numbers behind that last point are worse than most people expect.

WP Multitool measured an average autoload size of 4.2 MB across 50+ sites it optimised, against a healthy baseline of 200 to 500 KB reported by MakeWPFast.

XeroWP’s analysis found sites carrying 10 MB or more of autoloaded data hit frequent crashes and connection errors because the server runs out of memory before the first query finishes.

Plugin volume feeds this directly. SQ Magazine reports US WordPress sites run an average of 21 plugins each, and each one that calls addoption() without thinking sets autoload to yes by default.

WordPress 6.6 pushed back on that. Autoloaded options past a size threshold now get their autoload flag disabled automatically, which helps new bloat but does nothing for what already accumulated.

A failed schema update is the quieter cause. When dbDelta() stops halfway through creating a custom table, the plugin keeps querying a table that only half exists, and the result is usually a critical error notice rather than a clean database message.

How to Identify Which Database Error WordPress Is Throwing?

Enable WPDEBUGLOG, read /wp-content/debug.log, then check the raw MySQL error log. The debug log names the failing query and table. The MySQL log names the connection or engine fault. Read both before editing wp-config.php.

Diagnosis before repair. Running WPALLOWREPAIR on a site whose only problem is a wrong password wastes twenty minutes and teaches you nothing.

Three checks separate the possibilities fast:

  • Does wp-admin load while the public site fails? Points to a table fault, not a connection fault.
  • Do other sites on the same hosting account also fail? Points to the MySQL service.
  • Does a bare PHP connection script succeed? Points away from credentials entirely.

Query Monitor is worth installing on staging before you need it. It shows the initial options query time and total queries per page load, which makes autoload bloat visible instead of theoretical.

Reading debug.log Without Exposing Errors to Visitors

Add to wp-config.php above the “stop editing” line:

define('WPDEBUG', true); define('WPDEBUGLOG', true); define('WPDEBUGDISPLAY', false); define('SAVEQUERIES', true); `

WPDEBUGDISPLAY set to false is the part people skip. Leave it on and every visitor reads your database paths.

The same file also captures PHP notices, so the technique doubles as a way to show PHP errors in WordPress without touching the server config. For host-level faults, the WordPress error log in cPanel or Plesk carries entries that debug.log never sees.

Testing the Connection Outside WordPress

Drop a four-line script in the web root and hit it directly:

` <?php $link = mysqliconnect('localhost', 'dbuser', 'dbpass', 'dbname'); if (!$link) { die('Failed: ' . mysqliconnecterror()); } echo 'Connected.'; `

Connected means your credentials are fine and the problem is inside WordPress. A failure message names the exact refusal: access denied, unknown database, or connection refused.

WP-CLI does the same job in one line with wp db check. Delete the test script the moment you are done.

How to Fix Error Establishing a Database Connection?

Verify the four constants in wp-config.php against the host panel, correct DBHOST for your environment, confirm the database user still holds privileges, then check that MySQL is running. Repair tools come last, not first.

The error establishing a database connection message means WordPress reached the point of asking MySQL for data and got nothing back. Your content is untouched. The connection is the only thing broken.

EnvironmentTypical DB_HOST value
Standard cPanel shared hostinglocalhost
Kinsta managed hostinglocalhost (where specified by the site’s Kinsta configuration)
Remote or clustered databaseDatabase server hostname, e.g. mysql.hostname.com
Local development where localhost fails127.0.0.1

Fixing Wrong Credentials in wp-config.php

Open wp-config.php over SFTP and compare DBNAME, DBUSER, DBPASSWORD, and DBHOST against cPanel > MySQL Databases.

GoDaddy’s own support documentation lists updating these connection strings as the primary fix, which tells you how often it is the answer.

Watch for trailing spaces inside the quotes. Copy-paste from a hosting panel drags them in more often than you would think, and wp-config.php is one of the few files worth knowing when to edit directly.

Fixing an Incorrect DBHOST Value

Most hosts use localhost. Some do not, and no error message tells you which camp you are in.

Try 127.0.0.1 when localhost fails on a local stack, since the two resolve through different paths (socket versus TCP).

On managed platforms, pull the value from the host dashboard rather than guessing. Kinsta, WP Engine, and SiteGround each publish theirs.

Restoring Database User Privileges

A correct password with no privileges produces the same error as a wrong password.

Check and restore in three steps:

  • Open cPanel > MySQL Databases and confirm the user is still attached to the database
  • Grant ALL PRIVILEGES on that database to that user
  • Reset the password, then paste the new value into wp-config.php

Automated security tools sometimes strip privileges during a lockdown and never restore them.

How to Repair a Corrupted WordPress Database?

Export a backup first, then run the built-in repair page, phpMyAdmin’s Repair table operation, mysqlcheck -r, or wp db repair. Which one works depends entirely on the storage engine behind the damaged table.

This is the step most guides get wrong. All four methods issue MySQL’s REPAIR TABLE statement underneath, and that statement only operates on MyISAM, ARCHIVE, and CSV tables.

MethodCommand or pathEngine support / notes
Built-in WordPress repair page/wp-admin/maint/repair.phpCan run WordPress’s repair/optimize operations, but support depends on the database engine and available MySQL/MariaDB operations
phpMyAdminRepair table operationPrimarily useful for engines that support REPAIR TABLE, such as MyISAM, ARCHIVE, and CSV
Command linemysqlcheck -r -u user -p dbnameUses REPAIR TABLE; therefore mainly applies to MyISAM, ARCHIVE, and CSV
WP-CLIwp db repairRuns database repair operations through the database server; limitations depend on the storage engine

Snapshot before you touch anything: wp db export backup-pre-repair.sql or a mysqldump from the command line.

Repairing MyISAM Tables

MyISAM flags a table as crashed after an unclean shutdown and refuses to read it until the table is checked.

Add define(‘WPALLOWREPAIR’, true); to wp-config.php, load /wp-admin/maint/repair.php, run the repair, then delete the constant immediately. The page needs no login while that line exists.

Microsoft’s MySQL documentation is blunt about the underlying weakness: MyISAM does not guarantee a write reaches disk, so a system crash can corrupt tables and lose data.

Recovering InnoDB Tables

InnoDB has been the MySQL default since 5.5.5, which means nearly every modern WordPress install runs on it.

Run REPAIR TABLE against an InnoDB table and MySQL returns "The storage engine for the table doesn't support repair" and changes nothing.

What actually works: InnoDB self-repairs during service restart, and stubborn cases need innodbforcerecovery in my.cnf, stepped from level 1 upward, then an immediate dump of the readable data.

Levels above 4 can destroy data. Do not start there because a forum post told you to.

When Repair Fails and Reimport Is the Only Option

Repair failing twice on the same table means the table is past recovery, not that you ran the command wrong.

Dump what still reads, drop the damaged table, and reimport it from the last clean backup:

` wp db export salvage.sql mysql -u user -p dbname < last-good-backup.sql `

Platform limits matter here. WP Engine supports InnoDB only and does not offer MyISAM at all, so engine conversion is not an escape route on that stack.

How to Fix Missing or Mismatched Database Tables?

Compare $tableprefix in wp-config.php against the real prefix in phpMyAdmin, confirm all 12 core tables exist, and reimport any table the SQL dump failed to create. A "table doesn't exist" error is almost always a naming problem, not a data loss problem.

The 12 tables WordPress requires: wpposts, wppostmeta, wpoptions, wpusers, wpusermeta, wpterms, wptermmeta, wptermtaxonomy, wptermrelationships, wpcomments, wpcommentmeta, and wplinks.

Open phpMyAdmin and read the actual prefix off the table list. If the tables read wpxyposts and wp-config.php says wp, you found it in ten seconds.

Changing a prefix breaks two things that live inside the data itself.

` UPDATE wpoptions SET optionname = 'wpxyuserroles' WHERE optionname = 'wpuserroles'; UPDATE wpusermeta SET metakey = 'wpxycapabilities' WHERE metakey = 'wpcapabilities'; `

Miss those two rows and every user loses their role, including you. The site connects, loads, and locks you out of wp-admin.

Partial imports cause the other half of these errors.

A dump that stops at maxallowedpacket or the phpMyAdmin upload cap creates the first 40 tables and abandons the rest, which is the same class of size ceiling behind a request entity too large error.

Verify before you troubleshoot further: wp db query “SHOW TABLES;” lists exactly what made it across. Count them against your source database.

How to Fix WordPress Database Errors After a Migration?

Repair serialized data with a serialization-aware search and replace, correct siteurl and home in wpoptions, match the character set between source and destination, and confirm the target MySQL version accepts the dump's collation.

Migration errors behave differently from ordinary corruption. The database connects fine and the tables all exist, yet widgets vanish, theme settings reset, and half the media URLs point at the old domain.

Broken serialized data causes most of it. PHP stores arrays in wpoptions with a character count prefix, so a raw SQL find-and-replace on a domain name leaves the length count wrong and the entire value unreadable.

Use wp search-replace old-domain.com new-domain.com or the Better Search Replace plugin. Both unserialize, replace, and reserialize properly. Never run a plain SQL REPLACE() across wpoptions or wppostmeta.

Mismatched siteurl and home values send visitors to the old host and can produce a redirect loop that looks like a WordPress login error rather than a database problem.

Fix them directly in wpoptions, or hardcode both in wp-config.php while you sort out the rest:

` define('WPHOME', 'https://newdomain.com'); define('WPSITEURL', 'https://newdomain.com'); `

Collation conflicts are the sneaky one. A dump written as utf8mb4unicodeci imported into a database expecting utf8mb4generalci throws unknown collation errors mid-import and stops.

Version gaps make it worse. MySQL 8.0 writes utf8mb40900aici by default, which MySQL 5.7 cannot read at all, and W3Techs data shows 5.7 still runs on roughly 29.65% of WordPress sites.

Check the destination version before exporting, not after. A find-and-replace on the collation string inside the .sql file takes thirty seconds and saves an afternoon.

Then confirm the import landed: wp db query “SHOW TABLES;” again, followed by a load of the front page and one admin screen that reads a custom table.

How to Fix Database Errors Caused by Plugins and Themes?

Deactivate every plugin by renaming the plugins folder over FTP, then reactivate one at a time while watching debug.log. The plugin that reproduces the failing query is your source. Orphaned tables and runaway transients get cleaned after that.

Third-party code writes to the database far more aggressively than core does. Patchstack’s State of WordPress Security in 2025 found 96% of disclosed vulnerabilities sat in plugins rather than WordPress itself, and the same imbalance shows up in database faults.

Volume is the underlying problem. WordPress.org plugin directory data cited by TopSyde puts the average site at 23 active plugins in 2025, each shipping 4 to 8 updates a year.

That works out to somewhere between 90 and 180 update events annually. Any one of them can leave a half-built custom table behind.

The isolation sequence:

  • Rename /wp-content/plugins to plugins-off over SFTP, or run wp plugin deactivate –all
  • Load the site. If the database error clears, a plugin owns it
  • Rename the folder back, then activate plugins one by one, refreshing debug.log between each
  • Switch to Twenty Twenty-Four if all plugins come back clean, since the theme runs queries too

Elementor’s own troubleshooting data attributes roughly 70% of white screen incidents to plugin conflicts, which makes the folder rename the highest-value first move you have.

The usual suspects: caching plugins that build custom tables, WooCommerce regenerating its product lookup tables, and LMS or membership plugins running dbDelta() on activation.

WordPress 6.9 broke WooCommerce, Yoast SEO, and Elementor at launch, which FatLab documented as hitting millions of sites with auto-updates enabled.

Deleting a plugin rarely removes its tables. Run SHOW TABLES; and look for prefixes belonging to software you uninstalled two years ago, then drop them or let WP-Optimize handle the sweep.

Transients are the other leak. Plugins write them with expiry times that WP-Cron never gets around to clearing:

` SELECT COUNT(*) FROM wpoptions WHERE optionname LIKE 'transient%'; SELECT SUM(LENGTH(optionvalue)) FROM wpoptions WHERE autoload='yes'; `

Anything above one megabyte on that second query needs attention before it becomes an error while updating plugins or a full connection failure.

Themes deserve the same scrutiny. A page builder theme querying postmeta on every widget produces the same symptoms as a broken plugin, so a WordPress theme error and a database error often turn out to be the same incident.

How to Fix Database Errors Caused by Server Limits?

Raise maxconnections and maxuserconnections for "Too many connections", tune waittimeout and maxallowedpacket for "MySQL server has gone away", and add object caching to cut query volume. Intermittent errors point here, not at credentials.

ErrorVariable / condition to checkFix
Too many connectionsmax_connections, max_user_connectionsReduce connection usage, investigate long-running connections, and raise the limit if the server has enough resources. Object caching can reduce database workload but does not directly increase the connection limit.
MySQL server has gone awaywait_timeout, interactive_timeout, max_allowed_packet, server/network stabilityIncrease max_allowed_packet if packets are too large, adjust timeouts where appropriate, and check MySQL/server logs for dropped or restarted connections.
Table is marked as crashedTable engine, disk space, database/server logsFree disk space if necessary, then repair only if the storage engine supports repair operations. For InnoDB, use InnoDB-specific recovery or restore from backup rather than REPAIR TABLE.

Oracle’s MySQL reference sets the default maxconnections at 151, plus one reserved slot for an admin connection.

Shared hosting cuts far below that. HostGator caps simultaneous MySQL connections at 25 per cPanel account, which a moderate traffic spike or an aggressive crawler clears without much effort.

Three things generate connection pressure:

  • Slow queries holding connections open longer than they need to
  • Plugins that open connections and never close them
  • WP-Cron and third-party cron jobs firing during peak traffic

Object caching is the fix with the best return. WPThrill’s 2025 measurements put the query reduction from Redis Object Cache at 40% to 70%, which on a WooCommerce store is the difference between surviving a sale and not.

Find the offender before raising limits. Run SHOW PROCESSLIST during a failure and enable the slow query log with longquerytime at 2 seconds.

Memory pressure produces the same symptoms from a different direction. A PHP process that dies mid-query looks identical to a database timeout from the browser, so rule out a memory exhausted error before touching my.cnf.

Traffic spikes on undersized plans surface as a 503 service unavailable error as often as a database message. Both mean the same thing: the server ran out of something.

Long-running imports and cron jobs trip waittimeout and return a timeout error before finishing, which leaves half-written rows behind and starts the corruption cycle over again.

Downtime math justifies the hosting upgrade fast. ITIC’s 2024 survey found over 90% of mid-size and large enterprises lose more than $300,000 per hour of outage, against Gartner’s cross-industry baseline of $5,600 per minute.

How to Restore a WordPress Database From a Backup?

Export the broken database before overwriting anything, then restore with wp db import, the mysql command line, or phpMyAdmin. Command line handles dumps that exceed the phpMyAdmin upload cap. Merge recent content back from the salvaged export afterward.

Restore is the fallback when repair fails on an InnoDB table, and it is the only route back from a corrupted tablespace.

Export the damaged database first. Even a corrupted dump usually contains posts published since your last clean backup, and you cannot get those back once you overwrite.

MethodCommand or pathBest for
WP-CLIwp db import backup.sqlLarge or any-size dumps when SSH/WP-CLI access is available
MySQL clientmysql -u user -p dbname < backup.sqlLarge SQL dumps, especially when phpMyAdmin upload limits are restrictive
phpMyAdminImport tabSmall-to-medium dumps when SSH access isn’t available
UpdraftPlusExisting Backups → RestoreGuided restores for users who prefer a WordPress admin interface

UpdraftPlus sits on 3 million active installations and reports a 96% restore success rate from its own testing, which makes it the default recommendation for anyone without command line access.

Duplicator, BlogVault, and host-level snapshots from Kinsta, WP Engine, and SiteGround cover the same ground with daily retention.

Size limits kill more restores than corruption does. phpMyAdmin refuses uploads past the PHP ceiling, so either split the file with BigDump or raise uploadmaxfilesize and postmaxsize in the php.ini file.

After the import completes, verify in this order:

  • wp db query “SHOW TABLES;” to confirm the table count matches
  • Load the front page and one admin screen that reads a custom table
  • Check that siteurl and home point at the current domain

Merging recent posts back is manual work. Open the salvaged export, pull the wpposts and wppostmeta rows created after the backup timestamp, and insert them into the restored database.

Untested backups are not backups. Restore to a staging site once a quarter and confirm the site actually loads.

How to Prevent WordPress Database Errors from Recurring?

Cap post revisions, schedule cleanup of expired transients and spam, run automated off-server backups with retention, test updates on staging, and monitor query counts with Query Monitor. Prevention costs an hour a month and repair costs a weekend.

Revisions dominate the bloat. GigaPress found post revisions routinely account for 40% to 60% of all rows in wpposts on active multi-author sites, each one spawning matching rows in wppostmeta.

Cap them permanently in wp-config.php:

` define('WPPOSTREVISIONS', 5); define('EMPTYTRASHDAYS', 14); `

TaskFrequency
Clear expired transients and spam commentsWeekly
Run wp db optimize and clean up unnecessary revisionsMonthly
Audit for orphaned plugin tablesQuarterly
Test-restore a backup to a staging environmentQuarterly

PluginTheme’s threshold is worth writing down: wpoptions past 5 MB or wppostmeta past 100 MB means cleanup is overdue.

Spam accumulates quietly in wpcomments and wpcommentmeta long after you stop noticing it, and a scheduled purge beats any manual attempt to delete comments in bulk after the table has already grown.

Staging is the highest-leverage habit here. WP Engine’s 2025 developer survey reported teams using staging environments hit 72% fewer deployment-related outages and resolve the rest three times faster.

Almost nobody does it. Elementor’s data puts staging adoption among small business users at just 35%.

The cost of skipping it shows up in the downtime numbers. A StatusCake study found the average small business site loses 3.2 hours a month to unplanned outages, with update-related incidents responsible for 41% of them.

Testing on a clone first is also the only reliable defence against a WordPress upgrade error taking the database down mid-release.

Backups need three properties: automatic, off-server, and retained. A copy sitting on the same disk as the database it protects is decoration.

Set retention to at least 30 days. Corruption often goes unnoticed for a week, and a seven-day retention window means every backup you hold is already broken.

Clean out what you are not using. Deactivated plugins still ship code, and knowing how to remove inactive themes keeps the update surface small enough to actually manage.

Monitoring closes the loop. Query Monitor shows the initial options query time and total query count per page, so autoload creep becomes visible months before it takes the site down.

Pair it with uptime alerts from your host. Running a portfolio makes this non-negotiable, and the tooling for managing multiple WordPress sites handles scheduled optimisation across all of them from one dashboard.

FAQ on How To Fix WordPress Database Errors

Does a database error mean my content is gone?

No. A connection failure means WordPress cannot reach MySQL, not that rows were deleted.

Posts, pages, and media stay in the database exactly as they were. Fix the connection and everything returns.

Where is wp-config.php located?

In the WordPress root folder, alongside wp-load.php and the wp-content directory.

Some hosts place it one level above the web root for security. Open it over SFTP or the cPanel File Manager.

What DBHOST value should I use?

localhost works on most cPanel and managed hosting, including Kinsta.

Try 127.0.0.1 on local stacks where the socket path fails. Remote database setups need the full hostname from your host panel.

Is WPALLOWREPAIR safe to leave enabled?

No. While that constant sits in wp-config.php, anyone can load /wp-admin/maint/repair.php without logging in.

Run the repair, then delete the line immediately. Treat it as a temporary switch, never a permanent setting.

Why does phpMyAdmin say the storage engine does not support repair?

Your tables run on InnoDB, and MySQL’s REPAIR TABLE statement only works on MyISAM, ARCHIVE, and CSV.

InnoDB self-repairs on service restart. Serious corruption needs innodbforcerecovery or a restore from backup.

How do I fix a table prefix mismatch?

Compare $tableprefix in wp-config.php against the real prefix shown in phpMyAdmin.

Change one to match the other, then update the prefix-bound rows: wpuserroles in wpoptions and wpcapabilities in wpusermeta.

Why did my site break after migration?

A raw SQL find-and-replace corrupts serialized data by leaving character counts wrong.

Use wp search-replace or Better Search Replace instead. Both unserialize, swap the values, and reserialize correctly.

What causes “Too many connections”?

Your account hit the maxuserconnections ceiling. HostGator caps shared plans at 25 simultaneous connections.

Add Redis or Memcached object caching to cut query volume, then raise the limit or upgrade the plan.

Should I repair or restore first?

Export the damaged database, attempt repair, and restore only if repair fails twice on the same table.

Repeated failure means the table is past recovery. Reimport it from your last clean backup.

How often should I optimize the database?

Run wp db optimize monthly alongside revision and transient cleanup.

Cap revisions with define(‘WPPOSTREVISIONS’, 5); so wpposts stops growing unchecked between maintenance windows.

Conclusion

Knowing how to fix WordPress database errors is mostly about order of operations. Diagnose with debug.log, correct credentials, repair only when the storage engine supports it, restore when it does not.

Skip the diagnosis and you end up running mysqlcheck against a database whose only problem was a rotated password.

The repair is the easy half. Keeping the same fault from returning takes actual maintenance.

Cap revisions, clear expired transients, watch your autoload total, and run wp db optimize` on a schedule you actually keep.

Then do the one thing almost nobody does: restore a backup to staging and confirm it works.

An untested backup is a guess. Test it now, while your site is still up.