The “Error establishing a database connection” message is one of the most alarming things a WordPress site can show. There is no partial failure here – the entire site goes down. No frontend, no admin dashboard, no way to log in and investigate. WordPress cannot do anything without its database, and this error means the connection between PHP and MySQL has failed completely.
The good news is that the cause is almost always one of five things, and most of them are fixable in minutes once you know where to look.
What the error actually means#
WordPress connects to MySQL every time a page loads. When you visit a WordPress site, PHP reads the database credentials from
wp-config.php
, opens a connection to the MySQL server, and runs queries to fetch the content it needs to build the page. If any part of that chain fails – wrong credentials, MySQL not running, database does not exist, server overloaded – WordPress has nothing to display and shows this error instead.
The error appears on both the frontend and the admin dashboard. Unlike a plugin conflict or theme error (which might only break the frontend), a database connection failure takes down everything. You cannot fix it from inside WordPress – you need access to the server itself, either through SSH, SFTP, or your hosting control panel.
Understanding the connection chain helps narrow down the cause:
- PHP reads
DB_NAME,DB_USER,DB_PASSWORD, andDB_HOSTfromwp-config.php - PHP attempts a TCP or socket connection to the MySQL server at the specified host
- MySQL authenticates the username and password
- MySQL checks whether that user has permission to access the specified database
- WordPress runs its first query
The error can occur at any of these steps, and each step has different causes and fixes.
Cause 1: Wrong database credentials in wp-config.php#
This is the most common cause, especially after a migration, hosting change, or password reset. The credentials in
wp-config.php
no longer match what MySQL expects.
How to diagnose
Open
wp-config.php
via SSH or SFTP and check these four values:
define('DB_NAME', 'your_database_name');
define('DB_USER', 'your_database_user');
define('DB_PASSWORD', 'your_database_password');
define('DB_HOST', 'localhost');
Then verify each one against what MySQL actually has configured.
Test the credentials from the command line:
mysql -u your_database_user -p your_database_name
If this fails with “Access denied,” the username or password is wrong. If it fails with “Unknown database,” the database name is wrong.
If you have WP-CLI installed:
wp db check
This attempts a connection using the credentials in
wp-config.php
and reports whether it succeeds.
How to fix
If the password was changed (intentionally or by your hosting provider during a migration), update
wp-config.php
with the correct password. If you do not know the current password, reset it through your hosting control panel’s MySQL management, or via the command line:
ALTER USER 'your_database_user'@'localhost' IDENTIFIED BY 'new_password_here';
FLUSH PRIVILEGES;
Then update
wp-config.php
to match.
Common credential mistakes after migration:
- The database name changed but
wp-config.phpstill has the old name - The database host changed from
localhostto a remote hostname (some hosts use a separate database server) - The table prefix in
wp-config.phpdoes not match the actual table prefix in the database (this causes a different error – “WordPress database tables not found” – but is worth checking)
If you recently migrated your site, the WordPress migration guide covers the full process of updating credentials for a new environment.
Cause 2: MySQL server is not running#
If the MySQL service has stopped, no application on the server can connect to it – not just WordPress. This typically happens after a server reboot where MySQL did not start automatically, after a crash due to running out of memory, or after a failed MySQL update.
How to diagnose
Check whether MySQL is running:
# On systemd-based systems (most modern Linux)
systemctl status mysql
# or
systemctl status mariadb
If the output shows “inactive” or “failed,” MySQL is down.
You can also test connectivity directly:
mysqladmin ping -u root -p
If MySQL is running, this returns “mysqld is alive.” If not, it returns a connection error.
How to fix
Restart MySQL:
# MySQL
sudo systemctl start mysql
# MariaDB
sudo systemctl start mariadb
If MySQL fails to start, check the error log for the reason:
# Common log locations
sudo tail -50 /var/log/mysql/error.log
sudo tail -50 /var/log/mariadb/mariadb.log
Common reasons MySQL will not start:
- Out of disk space. MySQL needs space for temporary files, binary logs, and InnoDB transaction logs. Check with
df -h. - Out of memory. MySQL’s configured buffer pool size exceeds available RAM. This happens when other processes (like PHP) consumed memory that MySQL expected to use. The error log will say something like “cannot allocate memory.”
- Corrupted InnoDB tablespace. If the server lost power or was forcefully killed, InnoDB’s transaction log may be inconsistent. MySQL refuses to start until this is resolved (see Cause 4 below for database repair).
- Port conflict. Another process is already bound to port 3306.
If you are on shared hosting, you cannot restart MySQL yourself – contact your hosting provider. On a VPS, you have full control over the MySQL service.
Preventing MySQL from stopping
Ensure MySQL starts automatically after a reboot:
sudo systemctl enable mysql
If MySQL keeps crashing due to memory pressure, the server is likely overcommitted. Either reduce MySQL’s memory allocation (
innodb_buffer_pool_size
is the biggest knob) or upgrade the server’s RAM.
Cause 3: Database does not exist#
This sounds obvious, but it happens more often than you would expect. The database was accidentally deleted, or a migration created the WordPress files but not the database, or the
DB_NAME
value in
wp-config.php
has a typo.
How to diagnose
List all databases and check whether the one in
wp-config.php
exists:
mysql -u root -p -e "SHOW DATABASES;"
Compare the output to the
DB_NAME
value in
wp-config.php
. MySQL database names are case-sensitive on Linux, so
WordPress_DB
and
wordpress_db
are different databases.
How to fix
If the database genuinely does not exist, create it:
CREATE DATABASE wordpress_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
GRANT ALL PRIVILEGES ON wordpress_db.* TO 'your_database_user'@'localhost';
FLUSH PRIVILEGES;
Then import your database backup. If you do not have a backup, you will need to reinstall WordPress. This is why regular database backups are critical.
If the database exists but has a different name, update
wp-config.php
to match.
Cause 4: Corrupted database#
Database corruption means one or more tables have inconsistencies that prevent MySQL from reading them correctly. WordPress may show the database connection error, or it may show partial content with some pages or features broken.
Corruption is usually caused by the MySQL process being killed mid-write – a server crash, power loss, or out-of-memory kill by the operating system. It can also happen during disk failures, though this is rare with modern storage.
How to diagnose
If MySQL is running but WordPress cannot use the database, check the tables:
wp db check
WP-CLI will report which tables, if any, are corrupted. Without WP-CLI, use the MySQL client:
mysqlcheck -u root -p --check wordpress_db
This runs
CHECK TABLE
on every table in the database and reports the status.
How to fix
Using WP-CLI:
wp db repair
This runs
REPAIR TABLE
on all WordPress tables.
Using WordPress built-in repair:
Add this line to
wp-config.php
:
define('WP_ALLOW_REPAIR', true);
Then visit
https://yourdomain.com/wp-admin/maint/repair.php
in your browser. This page does not require authentication (which is why it must be enabled manually). Click “Repair Database” or “Repair and Optimize Database.”
Remove the
WP_ALLOW_REPAIR
line from
wp-config.php
immediately after – leaving it in place creates an unauthenticated endpoint that anyone can access.
Using mysqlcheck:
mysqlcheck -u root -p --repair wordpress_db
When repair is not enough:
If
REPAIR TABLE
fails, the corruption is too severe for in-place repair. Your options:
- Restore from a backup (the safest option)
- Export what you can, drop the corrupted table, and reimport:
mysqldump -u root -p wordpress_db wp_posts > wp_posts_backup.sql mysql -u root -p wordpress_db -e "DROP TABLE wp_posts;" mysql -u root -p wordpress_db < wp_posts_backup.sql
If the corruption happened unexpectedly and you did not make any server changes, investigate whether the server is having hardware issues or running out of memory. Repeated corruption points to an underlying problem. It can also indicate a compromise – see My WordPress site was hacked: what to do right now if you suspect unauthorized access.
Cause 5: Too many connections#
MySQL has a maximum number of simultaneous connections it will accept. When that limit is reached, new connections are refused and WordPress gets a connection error.
This typically happens during traffic spikes, when a plugin creates connections faster than they are released, or when MySQL’s connection limit is set too low for the number of sites on the server.
How to diagnose
If MySQL is running and credentials are correct but WordPress still cannot connect, check the current connection count:
mysql -u root -p -e "SHOW STATUS LIKE 'Threads_connected';"
mysql -u root -p -e "SHOW VARIABLES LIKE 'max_connections';"
If
Threads_connected
is at or near
max_connections
, you have hit the limit. See which connections are active:
mysql -u root -p -e "SHOW PROCESSLIST;"
This shows every active connection, which user owns it, and what query it is running. Look for:
- Sleeping connections that have been idle for a long time (a plugin is opening connections and not closing them)
- Many connections from the same user (one site is consuming a disproportionate number)
- Long-running queries that are blocking other queries from completing
How to fix
Immediate fix – kill idle connections:
-- Find and kill sleeping connections older than 60 seconds
SELECT CONCAT('KILL ', id, ';')
FROM information_schema.processlist
WHERE command = 'Sleep' AND time > 60;
Run the generated
KILL
statements to free up connections.
Increase the limit (if the server has enough memory):
SET GLOBAL max_connections = 300;
To make this permanent, add it to the MySQL configuration file (usually
/etc/my.cnf
or
/etc/mysql/my.cnf
):
[mysqld]
max_connections = 300
Each MySQL connection uses memory (roughly 5-10 MB per connection depending on configuration), so raising the limit without having enough RAM will cause MySQL to consume all available memory and crash – which brings you right back to Cause 2.
Reduce connection usage:
WordPress itself is generally efficient with database connections – it opens one connection per request and closes it when the page is done. Connection exhaustion usually comes from:
- Caching plugins that use MySQL for object caching instead of Redis or Memcached
- WooCommerce sites with background processes (scheduled tasks, queue workers) that each hold a connection
- Long-running cron jobs via
wp-cron.phpthat hold connections for minutes - Multiple WordPress installations on the same server sharing the same MySQL instance
If you are on shared hosting, you do not have access to MySQL’s global settings. Contact your host if you suspect connection limits are the problem.
Other causes#
Wrong DB_HOST value
Most WordPress installations use
localhost
as the database host because MySQL runs on the same server. But some hosting providers run MySQL on a separate server and require a specific hostname like
db.provider.com
or an IP address.
If you are seeing the error after setting up a new hosting account, check your provider’s documentation for the correct
DB_HOST
value.
localhost
is the most common value but not universal.
For sites that use a remote MySQL server, see How to allow remote MySQL connections for the full setup process including user grants and firewall configuration.
MySQL socket file missing
On Linux, when
DB_HOST
is set to
localhost
, PHP connects to MySQL via a Unix socket file rather than TCP. If the socket file path in PHP’s configuration does not match where MySQL creates it, the connection fails.
Check where MySQL creates the socket:
mysql -u root -p -e "SHOW VARIABLES LIKE 'socket';"
Compare this to PHP’s expected location:
php -i | grep mysql.default_socket
If they do not match, either update PHP’s configuration or add the socket path to
wp-config.php
:
define('DB_HOST', 'localhost:/var/run/mysqld/mysqld.sock');
WordPress multisite with wrong DB_HOST
WordPress multisite installations use the same database for all sites in the network. If the database connection fails, every site in the network goes down simultaneously. The diagnostic steps are the same, but the impact is larger. This is one of the architectural tradeoffs of multisite – see WordPress multisite hosting: what you need to know for a detailed discussion.
Quick diagnostic flowchart#
When you see “Error establishing a database connection,” work through this sequence:
- Can you connect to MySQL at all? Try
mysql -u root -pfrom SSH. If this fails, MySQL is not running (Cause 2). - Can you connect with the WordPress credentials? Try
mysql -u wp_user -p wp_database. If this fails with “Access denied,” the credentials are wrong (Cause 1). If it fails with “Unknown database,” the database does not exist (Cause 3). - Can WordPress run queries? Run
wp db check. If tables are corrupted, repair them (Cause 4). - Is MySQL refusing new connections? Check
Threads_connectedvsmax_connections. If at the limit, you have too many connections (Cause 5). - Is the socket file correct? If
DB_HOSTislocalhost, verify the socket path matches between MySQL and PHP.
Most cases are resolved at step 1 or 2. Steps 3-5 are less common but worth checking if the obvious causes are ruled out.
How Hostney prevents this error#
Several architectural decisions in Hostney’s hosting platform make this error significantly less likely to occur.
Per-account database isolation. Each hosting account gets its own MySQL users with explicit permissions scoped to that account’s databases. One customer’s runaway queries or excessive connections cannot starve another customer’s database access. This is the most common cause of “too many connections” errors on traditional shared hosting, and per-account isolation eliminates it.
Localhost connections only. PHP containers connect to MySQL via localhost, not over the network. This eliminates an entire category of connection failures – network timeouts, DNS resolution failures, firewall rules blocking port 3306, and packet loss between application and database servers. The connection path is as short as it can be.
Continuous health monitoring. The infrastructure monitors MySQL status on every server continuously. If MySQL goes down, the system detects it within 60 seconds and sends alerts. On traditional shared hosting, MySQL being down might not be noticed until customers report it.
Automatic database size management. Instead of letting a database grow until it crashes MySQL or fills the disk (which would take MySQL down for every customer on that server), Hostney automatically switches oversized databases to read-only mode. The site continues to serve existing content while the owner cleans up the data. This prevents the cascading failure where one customer’s data growth causes disk exhaustion that crashes MySQL for everyone.
Container isolation for PHP. Each website runs in its own isolated container with its own PHP process. A PHP process hanging or leaking connections in one container does not affect other containers on the same server. On traditional shared hosting, a single site with a connection leak can exhaust the MySQL connection pool for all sites.
The result is that “Error establishing a database connection” is almost always a credentials issue on Hostney – typically after manually editing
wp-config.php
or importing a database from another host. The infrastructure-level causes (MySQL down, too many connections, disk full) are handled by the platform before they affect your site.
Summary#
“Error establishing a database connection” means WordPress cannot talk to MySQL. The five causes, in order of likelihood, are: wrong credentials in
wp-config.php
, MySQL service not running, database does not exist, corrupted tables, and too many concurrent connections.
Start diagnosis by testing the MySQL connection from the command line using the credentials in
wp-config.php
. If you cannot SSH into the server, check your hosting control panel for MySQL management tools. For a deeper dive into connection timeout errors that happen intermittently (rather than constantly), see MySQL server has gone away: what it means and how to fix it.
Whatever the cause, the fix is usually straightforward once you identify which step in the connection chain is failing. The key is having server access (SSH or control panel) and a recent database backup – the error itself cannot be fixed from inside WordPress.