How to Fix the WordPress Error Establishing a Database Connection
A structured fix for WordPress database connection errors: verify wp-config credentials, test the database server, repair corrupted tables and prevent a repeat.
What the error actually tells you
When WordPress loads, the wpdb class tries to connect to the database server and select the database using the constants defined in wp-config.php: DB_NAME, DB_USER, DB_PASSWORD and DB_HOST. If wpdb::db_connect() cannot open a connection, WordPress stops and prints Error establishing a database connection. If the connection succeeds but the database cannot be selected, you get a related but distinct message: Cannot select database.
That distinction matters for diagnosis. A connection failure points at the server, the host name, the user or the password. A selection failure points at DB_NAME or at the user’s privileges on that specific database. Before touching anything, note which message you are seeing and whether it appears on the front end only or in the administration area as well.
Before you change anything
Take a snapshot of the current state. Note what happened right before the error appeared — a hosting migration, a password change, a plugin update, a traffic spike or a server reboot. WordPress documentation on backups recommends backing up the database “always before an upgrade or a move to a new location”, and the same logic applies to repair work: make a database dump before you start so you can always return to a known state.
Also check whether the failure is total or partial. If the front end shows the error but wp-admin shows a message suggesting the database may need repair, you are likely looking at corrupted tables rather than a credentials problem, and you can jump ahead to the repair step.
Step 1: Read the credentials in wp-config.php
Open wp-config.php in the WordPress root directory and inspect the four database constants. Compare them character by character with the values from your hosting control panel, not from memory. Three mistakes account for a large share of these errors:
- A database password that was changed in the hosting panel but never updated in
wp-config.php. This is the classic cause after a security cleanup or a host-side migration. - Passwords containing quote characters or trailing whitespace introduced during a copy-paste. Retype the value instead of pasting it if anything looks suspicious.
- A missing or partially deleted closing quote after an edit, which silently breaks the whole file and can also produce the white screen of death, a failure mode covered separately in our guide to WordPress 500 errors.
Do not change all four values at once. Edit one, reload the site, and observe the result. Changing several things in parallel makes it impossible to tell which fix worked.
Step 2: Verify DB_HOST
DB_HOST is the constant most often wrong after a move between servers. The default on most shared hosting is localhost, which makes MySQL connect through a local socket. Some hosts instead require a specific host name such as mysql.example.com, and a few managed platforms require an IP address such as 127.0.0.1 instead of localhost because the socket path differs.
Two variants are worth knowing:
- If the database server listens on a non-standard port, the port can be appended:
mysql.example.com:3307. Thewpdbclass parsesDB_HOSTthroughwpdb::parse_db_host(), which understands this host:port form as well as socket paths. - If the site was recently migrated, the old host’s database address may still be in place. The correct value is whatever the new host documents, and it is not always
localhost.
When in doubt, test both localhost and 127.0.0.1. They are not interchangeable: one goes through the socket, the other through TCP.
Step 3: Confirm the database server is actually running
If the credentials look right, the problem may sit outside WordPress. Check these in order:
- Is MySQL or MariaDB running on the server? On a VPS you control, check the service status and the server logs for restarts, out-of-memory kills or failed starts.
- Does the hosting status page report an incident? Shared hosts do have database outages, and in that case no change on your side will help.
- Are you hitting a connection limit? Hosts cap simultaneous connections per database user. Under a traffic spike, or with too many worker processes, new connections get refused even though the credentials are correct. The error then appears intermittently rather than constantly — a strong hint that this is the cause.
Intermittent errors after a traffic spike usually resolve themselves once load drops, but they should push you toward a caching layer or a higher plan rather than repeated manual fixes. For a longer view of how hosting decisions feed into total cost, see our breakdown of website total cost of ownership.
Step 4: Test the credentials outside WordPress
The point of this step is to separate “wrong credentials” from “WordPress problem”. With WP-CLI installed, run:
wp db cli
This opens a MySQL console using exactly the credentials from wp-config.php. If it connects, WordPress has everything it needs and the issue lies elsewhere — corrupted tables, a half-finished update, or a drop-in overriding the database layer. If it fails with an access denied error, the problem is the credentials, the host or the user’s privileges, and the error message from MySQL will usually say which.
On hosting without shell access, use phpMyAdmin from the control panel with the same credentials. The goal is identical: prove or disprove the credentials independently of WordPress.
If the connection works but the wrong database is selected, check DB_NAME against the actual database name and confirm the user has been granted privileges on that database specifically. A user can exist, connect successfully, and still have no rights on the database WordPress needs — that produces the Cannot select database path, where wpdb::select() builds a failure message and calls wpdb::bail().
Step 5: Repair corrupted tables
When wp-admin suggests the database needs repair, or when wp db cli connects fine but WordPress still fails, table corruption is the likely cause. WordPress ships a built-in repair script. To enable it, add this line to wp-config.php:
define( 'WP_ALLOW_REPAIR', true );
Then visit example.com/wp-admin/maint/repair.php and choose Repair or Repair and Optimize. The WordPress documentation for wp-config.php includes an important warning here: while this constant is defined, the repair page does not require a login, so anyone can reach it. Remove the line from wp-config.php as soon as the repair finishes.
With WP-CLI the same job is scriptable and requires no web-accessible flag:
wp db check
wp db repair
Run wp db check first to see the current state, then wp db repair if problems are reported. This is the same check-then-repair workflow we recommend as part of a wider WP-CLI maintenance routine, and it can be scheduled rather than run by hand.
Causes that are easy to miss
A few scenarios do not fit the steps above neatly:
- A host-side migration changed the database name, user or host without updating
wp-config.php. Hosting providers sometimes silently move accounts to new infrastructure. The fix is Step 1 and Step 2, with values from the host’s current documentation. - The
wp-content/db.phpdrop-in exists. Any code placed there replaces or extendswpdb, so a broken drop-in can cause connection failures that survive correct credentials. Rename it temporarily and see whether the error disappears. - Memory exhaustion on the server kills MySQL during page loads. The web server error log will show out-of-memory messages near the failure timestamps, and the fix is a server configuration change, not a WordPress one.
If the error appeared immediately after a plugin or core update, restore a database backup taken before the update, then redo the update in a controlled way instead of trying to repair forward through an unknown state.
Keeping this from happening again
Most connection errors fall into two groups: environment changes you did not authorise, and single points of failure you can mitigate. Three habits cover most of it. Keep database backups on a schedule and before every upgrade or migration, with copies stored off the server. Verify after any host-side change that credentials in wp-config.php still match what the host provides. And if intermittent connection limits keep appearing under load, treat that as a capacity signal, not a recurring nuisance.
If you would rather not debug this class of problem yourself, our WordPress development service covers database troubleshooting, migrations and ongoing maintenance, and the WordPress platform overview lists the work we typically do on these sites.
Official sources.
Use these references to verify platform-specific behavior and version details.
Continue with the surrounding work.
How to Troubleshoot a WordPress 500 Internal Server Error
How to Fix WordPress Missed Schedules and WP-Cron Problems
How to Fix WordPress Emails That Are Not Being Sent
Broader context from the YCTheme blog.
Total Cost of Ownership: What a Business Website Actually Costs to Run
A three-year cost framework for WordPress, Joomla, TYPO3 and Shopify websites, covering hosting, upgrades, security, extensions and the labor nobody budgets for.
Staging Environments: How Professional Teams Ship CMS Changes Without Breaking Production
Staging is where risky changes prove themselves before customers see them. A practical look at how WordPress, Joomla, TYPO3 and Shopify teams stage, test and promote changes.