Error establishing a database connection in WordPress: causes and step-by-step fixes
The Error establishing a database connection screen means WordPress could not create or maintain the connection it needs to MySQL or MariaDB. The browser does not reveal the exact cause. Incorrect credentials, an unavailable server, the wrong DB_HOST, missing privileges, exhausted limits, and damaged tables can all produce a similar message.
The greatest risk is random action. Replacing WordPress files, reinstalling plugins, or importing an old database is rarely the right first step. On a lead-generation or WooCommerce site, an uncontrolled restore may erase enquiries and orders created after the backup.
If the site generates revenue and no reliable backup or log access exists, use professional website technical support. For self-service diagnosis, follow the sequence below and record every change.
How the WordPress database connection works
WordPress content is not stored only in files. Pages, posts, users, settings, products, orders, and much plugin data live in the database. WordPress reads four core values from wp-config.php:
define( 'DB_NAME', 'database_name' );
define( 'DB_USER', 'database_user' );
define( 'DB_PASSWORD', 'database_password' );
define( 'DB_HOST', 'localhost' );
PHP then contacts the specified database host. MySQL verifies the account, password, allowed source, and privileges before accepting queries. A failure at any of these stages may lead to the same generic page.
Never paste production passwords into screenshots, chats, or support tickets. If a secret has been exposed, rotate it and update the configuration immediately.
Diagnostic map
| Symptom | Likely layer | First check |
|---|---|---|
| Constant error after migration | configuration | DB_NAME, DB_USER, DB_PASSWORD, DB_HOST |
| Error after a password change | credentials | database-user password and wp-config.php |
| Site works intermittently | capacity or availability | database logs, connections, CPU, RAM, disk |
| Every site on the account fails | database service | provider status and service health |
| Only one site fails | database or user | privileges, database name, damaged tables |
/wp-admin/ shows a different message |
tables or upgrade state | exact message and table status |
Log says Access denied |
authentication or privilege | account, password, host and grants |
MySQL server has gone away |
lost connection | timeout, packet, long query, server restart |
Use BB STUDIO website tools to confirm the HTTP response and headers of the failing URL. This helps distinguish an application failure from a cached page, redirect, or proxy response.
The first 15 minutes
- Open the site in a private window and from another network.
- Record the exact time, URL, and most recent known change.
- Test the homepage, an internal URL,
/wp-admin/, and the hosting status panel. - Do not clear every cache or import a backup before preserving the current state.
- Download
wp-config.phpand export the database if the panel still provides access. - Check whether other sites use the same database server and whether they work.
- Open MySQL/MariaDB, PHP, and system logs for the matching time.
- Test one hypothesis at a time.
Do not confuse this message with a general WordPress 500 Internal Server Error. A 500 response often involves PHP execution, a plugin, theme, or web-server rule, while the database message more specifically points to the data-connection stage.
Step 1: define the scope
One website fails
Start with its configuration, database, user, and privileges. If other projects on the same hosting platform work, a complete database-service outage is less likely.
Every website fails
When independent installations lose their databases at the same time, inspect the MySQL/MariaDB service, server load, storage, the network between web and database tiers, and provider maintenance.
The error is intermittent
If refreshing occasionally works, the credentials are probably valid. Look for connection exhaustion, MySQL restarts, locks, long queries, memory pressure, storage latency, or unstable networking. Automatic refreshing hides the incident; it does not remove the cause.
The error appears only during traffic spikes
Compare timestamps with advertising, product imports, backup jobs, cron, email campaigns, and bot traffic. A suitable website hosting environment needs observability and recoverability as well as nominal capacity.
Step 2: verify wp-config.php
Compare the file against current values in the hosting panel, not an old email or local copy.
DB_NAME
The database name must match exactly. Shared hosting often adds an account prefix. A migrated database may receive a new name even when the domain remains unchanged.
DB_USER
The database user is not necessarily the WordPress, FTP, or control-panel login. Confirm that the account exists and is attached to the intended database.
DB_PASSWORD
Passwords are case-sensitive and may contain special characters. A common failure occurs when the password is reset in the panel without updating wp-config.php. Ensure a rich-text editor has not changed straight quotes into typographic quotes.
DB_HOST
localhost is not universal. A provider may require a separate hostname, IP address, port, or socket. A value can look like db.example.host:3306. Never carry the old host into a migration without verifying it.
Syntax and invisible edits
Check straight quotes, semicolons, and accidental line breaks. Use a plain-text editor. Preserve a copy of wp-config.php outside the public directory before changing it.
Step 3: test the credentials separately
With SSH access, use the standard MySQL client with the same host, user, and database. Avoid putting the password directly into a shell command where it may remain in history. On managed hosting, use the supported database tool or ask the provider to test connectivity from the web node.
The response narrows the problem:
Access denied for usersuggests the wrong password, account, allowed host, or privileges;Unknown databasepoints to the wrong name or a deleted database;Can't connect to MySQL serversuggests the wrong host or port, a stopped service, or a network block;Connection refusednormally means no service is accepting the connection at that endpoint;- a timeout points toward networking, firewall, overload, or a stuck server.
If the standalone connection succeeds but WordPress fails, compare the PHP environment, the configuration file actually loaded, a db.php drop-in, and environment-variable overrides.
Step 4: inspect the user and privileges
A valid password does not guarantee access to the intended database. MySQL considers both the account and the connection source. After migration, a user may exist but not be assigned to the new database or may lack required privileges.
On shared hosting:
- verify the user-to-database mapping in the panel;
- reassign the required privileges through the supported interface;
- avoid global rights across unrelated databases;
- test both reading and writing through WordPress;
- document the exact change.
Do not paste arbitrary GRANT ALL commands into production. Excessive privileges increase the impact of compromise, and an incorrect host match can still block the connection.
Step 5: check MySQL/MariaDB and resources
When configuration is correct, inspect infrastructure:
- the database service is running;
- the required port or socket is listening;
- storage and inodes are available;
- concurrent-connection limits are not exhausted;
- sufficient memory is available;
- the service is not restarting repeatedly;
- the database endpoint is reachable from the web server;
- the firewall allows the route;
- the account has not exceeded a quota.
For intermittent incidents, align CPU, RAM, disk I/O, and connection graphs with the precise error time. Daily averages often conceal a short spike that breaks checkout.
Step 6: inspect tables and the database upgrade state
If WordPress can reach the server but reports unavailable or damaged tables, do not immediately repair everything. Capture a current database dump and review logs first.
WordPress provides a repair mode:
define( 'WP_ALLOW_REPAIR', true );
This enables /wp-admin/maint/repair.php. The utility can be available without authentication, so remove the constant immediately after use. Repair cannot restore deleted records, replace a backup, or correct a storage or hardware failure.
Before repair, identify:
- the affected tables;
- their storage engine;
- the most recent usable backup;
- available disk space;
- whether orders or leads are still being written;
- provider restrictions, replication, or managed-service rules.
For a complex database, test repair on a copy or staging environment. An unsuccessful operation on the only production database may make later recovery harder.
Step 7: audit migration and environment variables
Post-migration failures often come from an incomplete dependency map. Confirm that:
- the database was imported into the intended server;
- a user was created and assigned privileges;
DB_HOSTor the port did not change;- deployment secrets in
.envor the platform are current; - WordPress is loading the expected
wp-config.php; - an old hosting-specific
wp-content/db.phpwas not carried over; - object-cache settings do not reference a retired service;
- the new web node can reach a private database endpoint.
Professional website development should include environment documentation, a controlled migration, and a tested rollback path rather than file copying alone.
WooCommerce requires a separate recovery plan
An ecommerce database changes constantly. Orders, payment states, stock, carts, sessions, and webhooks may be written every minute. Rolling the entire database back to yesterday can make the storefront available while losing new sales.
Before recovery:
- place the store into controlled maintenance when possible;
- preserve the current database even if it is partially damaged;
- review payment-gateway logs and the acquiring account;
- list transactions created after the selected backup;
- decide whether table-level recovery is safer than a full rollback;
- reconcile payments, orders, stock, and email after launch.
Do not ask a customer to pay again until the transaction status is known. A missing WooCommerce order does not prove that no money was captured.
When the incident may be a security problem
An unexplained password change, unknown database user, modified wp-config.php, foreign db.php, new cron entries, or sudden query volume can indicate compromise.
In that case:
- preserve logs and a forensic copy;
- rotate hosting, SSH/SFTP, database, and WordPress credentials;
- review administrators and access keys;
- scan files and compare WordPress core;
- inspect plugins, mu-plugins, cron, and drop-ins for persistence;
- update WordPress salts;
- identify and close the original entry point.
Restoring the old password alone leaves the cause and any persistence mechanism in place.
SEO and advertising impact
A short isolated outage is unlikely to destroy rankings, but prolonged or repeated failures interrupt crawling, block purchases, and waste paid traffic. Do not serve a database error with 200 OK. A controlled 503 Service Unavailable response is more appropriate for a temporary outage, although implementation depends on the infrastructure.
After recovery, test important URLs, sitemap, robots, canonicals, forms, and checkout. Review Search Console and logs if the outage was prolonged. Effective SEO support includes availability and technical health, not keywords alone.
Proving that recovery is complete
Do not stop after the homepage opens. Test:
- dashboard login and content saving;
- creating and updating a post;
- lead-form submission and delivery;
- search, filters, and customer accounts;
- cart, checkout, and a test payment;
- scheduled tasks and webhooks;
- new MySQL and PHP log entries;
- load and active connections;
- a fresh post-recovery backup.
Document the root cause precisely: “database password changed without a configuration update,” “connections exhausted during an import,” or “old host remained after migration.” “Restarted the server” records an action, not the cause.
Prevention checklist
- Manage configuration and secrets through a controlled process.
- Back up files and the database to separate storage automatically.
- Test restores rather than checking only that archives exist.
- Monitor HTTP status, MySQL connections, disk, CPU, and memory.
- Alert on low storage and database unavailability.
- Use staging and a rollback plan for updates and migrations.
- Document the database host, port, owner, and provider contact.
- Restrict the database user to the required database.
- Keep production passwords out of public repositories.
- Remove the root cause after every incident.
Service benchmarks are available on the BB STUDIO pricing page, with completed work shown in the portfolio.
Final checklist
- the time, URL, and latest change are recorded;
- persistent and intermittent failure have been distinguished;
- current files and database are preserved;
DB_NAME,DB_USER,DB_PASSWORD, andDB_HOSTare verified;- credentials are tested separately;
- the user is assigned to the correct database;
- MySQL, port, socket, disk, and connections are checked;
- repair runs only after a backup;
WP_ALLOW_REPAIRis removed after use;- WooCommerce payments and recent orders are reconciled;
- writes, forms, cron, and checkout are tested;
- a fresh recovery-point backup is created;
- the root cause is documented.
If the error returns or no safe backup exists, contact BB STUDIO for controlled diagnosis and recovery.
Conclusion
Error establishing a database connection is not a complete diagnosis. It signals a break somewhere in the WordPress-to-network-to-MySQL-to-database chain. The shortest route to the cause is to define the scope, preserve the current state, verify the four wp-config.php values, test the credentials independently, inspect privileges and service health, and only then repair tables or restore data.
Sequence matters more than the number of attempted fixes. One evidence-backed change with a rollback point is safer than ten guesses on production.
Frequently asked questions
What does Error establishing a database connection mean?
WordPress could not connect to MySQL/MariaDB or lost the connection. Incorrect credentials, an unavailable service, missing privileges, resource limits, or damaged tables may be responsible.
Can the error be fixed without dashboard access?
Yes. Diagnosis typically uses file or SFTP access, wp-config.php, the database panel, and hosting logs. The dashboard itself depends on the database.
Will restoring a backup solve the problem?
Only when the cause is data or table damage and the backup is usable. A wrong password, DB_HOST, or unavailable MySQL server is not fixed by importing data. A full ecommerce rollback can also lose new orders.
Is WP_ALLOW_REPAIR safe?
Use it only after a backup and when table damage is suspected. The repair page can be accessible without login, so remove the constant immediately after finishing.
Why does the error occur only sometimes?
Intermittent failures often indicate connection exhaustion, load, database restarts, long queries, resource pressure, or network instability rather than a permanently wrong password.






