“Error establishing a database connection” means WordPress cannot reach its MySQL or MariaDB database. The usual causes are wrong credentials in wp-config.php, a database server that is down or overloaded, or a corrupted database. Fix it by reading the real MySQL error, then correcting that cause. WPOptimizers can restore the site if needed.
This error stops your whole site at once. Visitors see one line of text, and wp-admin often shows the same message, so you can’t log in to fix it.
The good news: your content is almost always safe. This guide shows you how to find the exact reason WordPress can’t connect, fix it safely, and stop it from happening again, including causes most guides miss, like full disks, connection limits and Multisite settings.
How Do You Fix “Error Establishing A Database Connection”?
Fix the error establishing a database connection by turning on debugging to read the real MySQL error, checking DB_NAME, DB_USER, DB_PASSWORD and DB_HOST in wp-config.php, confirming the database server is running, and repairing the database if tables are damaged. WPOptimizers follows this order because it finds the cause fastest.
Here are the 9 fixes in this guide, in the order to try them:
- Read the real MySQL error with WP_DEBUG
- Check the database credentials in wp-config.php
- Confirm the DB_HOST value, port and socket
- Check the database user’s privileges
- Test the connection directly
- Check whether the database server is down or overloaded
- Repair the WordPress database safely
- Free up disk space and check PHP extensions
- Fix migration, table prefix and Multisite settings
Work from the top. Most sites are fixed in the first three steps.
What Does “Error Establishing A Database Connection” Mean?
The message means WordPress tried to connect to its database and failed. WordPress stores posts, pages, users, settings and orders in a MySQL or MariaDB database. On every page load it connects using the details in wp-config.php. If that connection fails, WordPress shows this error instead of your site.
The page is plain text with no theme or design, because WordPress can’t load anything without the database.
You may see a slightly different message in wp-admin, such as “One or more database tables are unavailable. The database may need to be repaired.” That means WordPress connected, but some tables are damaged.
WPOptimizers sees this error most often after host migrations, password changes, traffic spikes and shared hosting outages.
What Causes The Error Establishing A Database Connection?
The most common causes are wrong database credentials, an incorrect DB_HOST value, a database user without the right privileges, a database server that is down or out of connections, corrupted tables, a full disk, and mistakes after migration. The exact MySQL error code usually tells you which one you’re dealing with.
| MySQL Error Shown | What It Means | Likely Fix |
| 1045 Access denied for user | Wrong username or password | Correct DB_USER and DB_PASSWORD |
| 1044 Access denied to database | User lacks privileges on that database | Assign the user with all privileges |
| 1049 Unknown database | Database name is wrong or missing | Correct DB_NAME or restore the database |
| 2002 Connection refused / No such file | Server down, wrong host or wrong socket | Check DB_HOST and server status |
| 2005 Unknown MySQL server host | DB_HOST hostname can’t be found | Use the host value from your provider |
| 1040 Too many connections | Server hit its connection limit | Reduce load and ask the host to review limits |
| 2006 MySQL server has gone away | Server crashed, restarted or timed out | Check server health and resources |
Note what changed recently. A password change, a new host or a traffic spike is often the whole story.
What Should You Do Before You Start Troubleshooting?
Before you change anything, back up your files and database, download a copy of wp-config.php, and check whether other sites on the same hosting account work. Also look at your host’s status page. These checks take minutes and often show whether the problem is your site or the server.
- Download wp-config.php from your site root (usually
public_html) through FTP or File Manager. - Back up the database with your host’s backup tool or by exporting it in phpMyAdmin, if it opens.
- Check other sites on the same account. If they show the same error, the database server is likely down.
- Check your host’s status page or support channel for a known outage.
- List recent changes: new host, password reset, plugin installs, traffic spikes or a domain change.
If you need a clean copy later, this guide shows how to restore WordPress from backup. WPOptimizers always takes a fresh backup before touching a broken site.
How Do You Find The Real MySQL Error Behind The Message?
Turn on WordPress debugging in wp-config.php, then reload the site. WordPress writes the underlying MySQL connection error, such as “Access denied” or “Connection refused,” to wp-content/debug.log. That message, and its error code, tells you which fix to apply instead of guessing.
Add or edit these lines above “That’s all, stop editing!”:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
A typical entry looks like this:
PHP Warning: mysqli_real_connect(): (HY000/1045): Access denied for user 'site_user'@'localhost'
Match the code to the table above. 1045 points to credentials, and 2002 points to the server or host.
Keep WP_DEBUG_DISPLAY off so database details never appear on screen. When the site works again, set WP_DEBUG back to false and delete debug.log.
WPOptimizers reads this log first on every database error, because it turns a vague message into a specific fix.
How Do You Check Your Database Credentials In wp-config.php?
Open wp-config.php and compare DB_NAME, DB_USER, DB_PASSWORD and DB_HOST with the details in your hosting panel. One wrong character breaks the connection. If you’re unsure of the password, reset it in your hosting panel and paste the new one into wp-config.php.
Look for these lines:
define( 'DB_NAME', 'database_name_here' );
define( 'DB_USER', 'username_here' );
define( 'DB_PASSWORD', 'password_here' );
define( 'DB_HOST', 'localhost' );
In cPanel, open MySQL Databases. The database name and user appear under Current Databases and Current Users. Many hosts add a prefix, such as account_dbname, which must be included exactly.
Watch for these common mistakes:
- A missing account prefix on the database name or username.
- Extra spaces copied before or after a value.
- A password containing a single quote
', which breaks the line. Change the password, or escape the quote. - Editing a copy of wp-config.php instead of the live file.
Save the file and reload the site. WPOptimizers fixes most database errors at this step.
Is Your DB_HOST Value Correct?
Most hosts use localhost as DB_HOST, but managed WordPress and cloud hosting often run the database on a separate server. They then need a hostname, an IP address, a port number or a socket path. If DB_HOST is wrong, you’ll usually see error 2002 or 2005.
Common DB_HOST formats include:
localhost– the database runs on the same server.127.0.0.1– works whenlocalhostfails because of socket settings.localhost:3306– a custom port.localhost:/var/run/mysqld/mysqld.sock– a custom socket path.db.example-host.com– a remote database server.
Get the exact value from your hosting dashboard or support team. Don’t guess on managed hosting.
If your current host makes database settings hard to manage, compare managed vs shared hosting or browse cloud hosting providers in the USA.
Does The Database User Have The Right Privileges?
A database user can exist with the correct password and still fail to connect if it isn’t assigned to the database or lacks privileges. Error 1044 is the usual sign. In your hosting panel, add the user to the database and grant all privileges, then reload the site.
In cPanel, go to MySQL Databases → Add User to Database, choose the user and database, then tick All Privileges.
On VPS and local setups, the user may be restricted to the wrong host. For example, a user allowed only from one address won’t connect from localhost. Your host or server admin can check this.
Privilege problems are common after migrations, where the database is imported but the user is never linked to it. WPOptimizers checks this on every move.
How Do You Test The Database Connection Directly?
Test the connection outside WordPress with a small PHP script or WP-CLI. If the test connects, WordPress settings are the problem. If it fails, the issue is the credentials, the user or the database server. Delete the test file immediately afterwards, because it contains your database password.
Create db-test.php in your site root:
<?php
$link = mysqli_connect( 'localhost', 'db_user', 'db_password', 'db_name' );
if ( ! $link ) {
die( 'Connection failed: ' . mysqli_connect_error() );
}
echo 'Connected successfully';
mysqli_close( $link );
Replace the four values with yours, then visit yourdomain.com/db-test.php. The script uses mysqli_connect_error(), which shows the real reason a connection failed.
With SSH access, WP-CLI offers a safe check:
wp db check
Delete db-test.php as soon as you’ve finished. WPOptimizers never leaves test scripts on a live server.
Is The Database Server Down Or Overloaded?
If credentials are correct but the connection still fails, the database server may be down, restarting, or out of connections. Shared hosting often hits limits during traffic spikes, bot attacks or heavy background jobs. Error 1040 or 2006, or the same error on all your sites, points here.
Common causes of overload include:
- Traffic spikes from a viral post or a campaign.
- Bad bots and brute-force attacks on
wp-login.phpandxmlrpc.php. - Heavy cron jobs, imports or backups running at busy times.
- Slow database queries from poorly built plugins.
- Connection limits such as
max_connectionsormax_user_connectionson shared plans.
Contact your host and ask whether MySQL is running and whether you’ve hit a limit. On a VPS or dedicated server, restarting the MySQL or MariaDB service may restore access.
Reduce load with page caching and an object cache like Redis, and block abusive bots. If limits keep returning, upgrade to the best WordPress hosting for speed.
How Do You Repair A Corrupted WordPress Database?
If WordPress connects but reports unavailable or damaged tables, repair the database. Add WP_ALLOW_REPAIR to wp-config.php, visit /wp-admin/maint/repair.php, and click Repair Database. You can also use your hosting panel or WP-CLI. Remove the repair line immediately afterwards, because the page works without logging in.
Add this line above “That’s all, stop editing!”:
define( 'WP_ALLOW_REPAIR', true );
Then visit yourdomain.com/wp-admin/maint/repair.php and choose Repair Database or Repair and Optimize Database.
In cPanel, go to MySQL Databases → Modify Databases → Repair Database. With SSH, run wp db repair.
Some commands found online are dangerous. Know the difference before running anything:
| Command Or Action | What It Does | Safe? |
wp db check | Checks tables for errors | Yes |
wp db repair | Repairs damaged tables | Yes, after a backup |
| WP_ALLOW_REPAIR page | Repairs and optimizes tables | Yes, then remove the line |
wp db export | Saves a backup of the database | Yes |
wp db reset | Deletes every table in the database | No – it erases the site |
wp db drop | Deletes the whole database | No – it erases the site |
Never run reset or drop to “fix” a connection error. WPOptimizers always exports the database before any repair.
Can A Full Disk Or Missing PHP Extension Cause This Error?
Yes. A full disk or database quota stops MySQL from writing data, which can break connections. A missing PHP MySQL extension, often after a PHP version change, stops PHP from talking to the database at all. Both show up as connection errors even when credentials are correct.
Check storage in your hosting panel. Old backups, large log files and unused media often fill space without warning. Delete or move them, then reload the site.
If you see “Your PHP installation appears to be missing the MySQL extension,” ask your host to enable the mysqli extension for your PHP version. Then confirm you’re on a PHP version WordPress currently supports.
WPOptimizers monitors disk usage and PHP versions on maintained sites, so neither problem appears unexpectedly.
Why Does The Error Appear After A Migration?
After moving hosts, the database connection error usually comes from new credentials that weren’t updated in wp-config.php, a user not linked to the new database, a different DB_HOST, or an import that failed. A wrong table prefix shows the WordPress install screen instead, which means WordPress can’t find your tables.
Check these after any migration:
- Update DB_NAME, DB_USER, DB_PASSWORD and DB_HOST to the new host’s values.
- Confirm the database import finished and the tables exist in phpMyAdmin.
- Match
$table_prefixin wp-config.php to your table names, such aswp_orabc_. - Confirm
siteurlandhomein thewp_optionstable use the correct domain. - For Multisite, update
wp_siteandwp_blogsand the DOMAIN_CURRENT_SITE value in wp-config.php.
Use a serialization-safe search-and-replace tool when changing domains, as plain text edits can break stored settings.
WPOptimizers runs migrations with a checklist that covers every item above before DNS is switched.
Why Does The Error Come And Go?
An error that appears and disappears usually points to server limits, not wrong credentials. Shared hosting may reject connections during busy periods, a crashing MySQL service may restart itself, or a CDN or cache may keep serving an old error page. Note when it happens to spot the pattern.
- Busy times: check whether errors match traffic peaks, cron schedules or backups.
- Server restarts: ask your host for MySQL uptime and crash logs.
- Cached error pages: purge your caching plugin, hosting cache and CDN after the fix, and test in a private window.
- Bot traffic: look for floods of requests to
wp-login.phporxmlrpc.phpin server logs.
If outages repeat, the hosting plan is often too small for the site. WPOptimizers reviews server logs to tell the difference.
Database Error Still Taking Your Site Down?
If the fixes above haven’t worked, or you’d rather not edit wp-config.php on a live site, WPOptimizers WordPress developers can find the cause, reconnect your database and check that forms, checkout and key pages work.
Can Corrupted Core Files Or A Hack Cause The Error?
Yes. A failed update can damage core files that handle the database connection, and a hacked site may have a modified wp-config.php or changed database passwords. Replace core files with a fresh copy, review wp-config.php for unknown code, and change the database password if you suspect a hack.
To replace core files safely, upload fresh wp-admin and wp-includes folders from the same WordPress version. Never overwrite wp-content or wp-config.php.
Signs of a hack include unknown code at the top of wp-config.php, new admin users and redirects to spam sites. Scan with a WordPress security plugin, change all passwords, and follow these steps on how to secure a WordPress site.
Keep wp-config.php tightly protected. This WordPress file permissions guide explains safe settings. WPOptimizers locks down wp-config.php on every maintained site.
How Do You Show Visitors A Friendly Page During A Database Outage?
Create a file named db-error.php inside wp-content. WordPress loads it automatically when the database connection fails, so visitors see a branded message instead of plain text. Send a 503 status code so search engines know the outage is temporary and come back later.
<?php
header( 'HTTP/1.1 503 Service Temporarily Unavailable' );
header( 'Retry-After: 600' );
?>
<!DOCTYPE html>
<html><head><title>Back Soon</title></head>
<body>
<h1>We'll be right back</h1>
<p>Our site is having a temporary technical issue. Please try again in a few minutes.</p>
</body></html>
Keep it simple with no database calls, since the database is unavailable.
Add a phone number or email so customers can still reach you. WPOptimizers adds this file to client sites as a standard safety step.
How Do You Prevent Database Connection Errors?
Prevent database connection errors by choosing hosting with enough resources, keeping daily offsite backups, using page and object caching to reduce database load, blocking abusive bots, keeping PHP supported, monitoring disk space, and using uptime monitoring. A WordPress maintenance plan handles these tasks for you.
- Right-size your hosting so traffic peaks don’t exhaust connections.
- Back up daily and store copies offsite. See how to back up your WordPress site daily.
- Use caching to cut database queries on every page view.
- Block bad bots and limit access to
xmlrpc.phpandwp-login.php. - Optimize the database by clearing spam comments, old revisions and expired transients.
- Watch disk space and remove old backups and logs.
- Monitor uptime so you hear about outages in minutes.
WordPress maintenance plans from WPOptimizers start at $49 per month and keep backups, updates and site health under control.
Frequently Asked Questions About The Database Connection Error
These answers cover the questions site owners ask most about the error establishing a database connection, including data safety, SEO, time to fix, plugins, cPanel access and hosting support, based on the fixes WPOptimizers uses when repairing client websites.
Will I Lose My Content Because Of This Error?
Usually not. The error means WordPress can’t reach the database, not that the database is gone. Posts, pages and orders normally stay intact. Data is at risk only if the database is deleted or badly corrupted, or if someone runs a destructive command like wp db reset. Always back up before repairs.
Does A Database Connection Error Hurt SEO?
A short outage rarely causes lasting SEO damage, especially if your site returns a 503 status through db-error.php. Long or repeated outages can cause pages to drop from search results and lose traffic. Fix the cause quickly and monitor uptime. Not every ranking drop is downtime, as explained in this guide to rankings that fluctuate without a Google update.
Can A Plugin Or Theme Cause This Error?
Rarely as a direct cause. Plugins and themes don’t control database credentials. However, a plugin running heavy or slow queries can overload the database server and trigger connection limits. If errors match plugin activity, such as imports or backups, test with that plugin disabled.
How Long Does It Take To Fix?
Credential and DB_HOST mistakes can be fixed in minutes once you see the real MySQL error. Server outages depend on your host’s response time. Corrupted databases, migrations and hacked sites take longer and may need a WordPress developer.
Can I Fix This Error Without cPanel?
Yes. You can edit wp-config.php through FTP or SFTP, repair the database with the WP_ALLOW_REPAIR page, and check connections with WP-CLI if you have SSH access. Managed hosts often provide their own dashboard tools or will update database settings for you through support.
Is WP_ALLOW_REPAIR Safe To Use?
Yes, if you remove it straight away. The repair page works without logging in, so anyone who finds the URL could run it while the line remains in wp-config.php. Add the line, run the repair, then delete it immediately.
Why Does wp-admin Show “One Or More Database Tables Are Unavailable”?
That message means WordPress connected to the database but found damaged or missing tables. Use the WP_ALLOW_REPAIR page or your hosting panel’s repair tool. If tables are missing entirely, restore the database from a recent backup.
Can My Hosting Provider Fix This Error?
Your host can check whether MySQL is running, confirm credentials and DB_HOST, raise connection limits, free disk space and restore database backups. They usually won’t fix plugin queries or site-level settings. For those, a WordPress developer or a maintenance provider like WPOptimizers can help.
What Should You Remember When WordPress Can’t Reach Its Database?
Remember that this error is a connection problem, not lost content. Read the real MySQL error, check wp-config.php and DB_HOST, confirm the server is healthy, and repair tables only after a backup. WPOptimizers recommends fixing the root cause, such as hosting limits, so the error doesn’t return.
- Your content is usually safe, so don’t delete anything in a panic.
- Turn on WP_DEBUG_LOG to see the real MySQL error code.
- Check DB_NAME, DB_USER, DB_PASSWORD and DB_HOST character by character.
- Make sure the database user has all privileges on the database.
- Never run
wp db resetorwp db dropto fix a connection error. - Remove WP_ALLOW_REPAIR and test scripts right after using them.
- Add a db-error.php page that returns a 503 status.
- Prevent repeats with good hosting, caching, backups and uptime monitoring.
What Is The Fastest Way To Fix A Database Connection Error?
The fastest route is to read the real MySQL error in debug.log, then fix what it points to. Error 1045 means credentials, 2002 means the host or server, and 1040 means connection limits. Most sites come back within minutes once the cause is clear, and WPOptimizers can step in when it isn’t.
After the site is back, ask why it happened. A one-off typo needs no follow-up, but repeated outages usually mean the hosting plan or database load needs attention.
Keep Your Database And Website Healthy
WPOptimizers WordPress maintenance plans start at $49 per month, with managed updates, daily backups and site monitoring, so database problems are caught early and fixed before your visitors notice.