🎉 PAYMENT SYSTEM LIVE! Buy points instantly - Starting $2.99 for 200 points!
💰 NEW PRICING: WP Error Expert 12 points + Blog tools FREE forever!
Skip to content
Home » How to Fix “Error Establishing a Database Connection” in WordPress: Complete Guide (2025)

How to Fix “Error Establishing a Database Connection” in WordPress: Complete Guide (2025)

Frustrated web developer at 3 AM troubleshooting WordPress database connection error on laptop with coffee cup

Your WordPress site is down. Instead of your homepage, you see a plain white screen with one devastating message:

“Error establishing a database connection.”

No dashboard access. No content. Just that error message staring back at you.

I’ve been there. Last year, ceeveeglobal.com went down because of this exact error. I was half-asleep, panicking, thinking I’d lost everything. Turns out, it was a simple fix — but only after I understood what was actually broken.

Here’s the thing: this error means WordPress can’t talk to your MySQL database. Your content is still there (probably), but WordPress can’t access it. The good news? In most cases, you can fix this yourself in 10-30 minutes without any data loss.

In this guide, I’ll walk you through exactly how to diagnose and fix this error, whether you’re on shared hosting or managing your own VPS. I’ll show you the actual commands I used, the mistakes I made (so you don’t repeat them), and how to prevent this from happening again.

Let’s get your site back online.

What Is the “Error Establishing a Database Connection”?

This error appears when WordPress cannot connect to your MySQL database. Think of it like this: WordPress is trying to make a phone call to your database, but the call won’t go through.

What WordPress Needs to Connect

Every time someone visits your WordPress site, WordPress needs to:

  1. Read your database credentials from wp-config.php
  2. Connect to your MySQL server using those credentials
  3. Query the database for posts, pages, settings, and user data
  4. Display that content on the screen

When any step in this process fails, you get the database connection error.

Why This Error Happens

The most common causes:

  • Wrong database credentials in wp-config.php (70% of cases)
  • Database server is down or unreachable (15% of cases)
  • Corrupted database tables (10% of cases)
  • Too many simultaneous connections (exceeded limits)
  • Database user permissions removed or changed
  • Server hostname changed (after migration or hosting change)

Before You Start: Critical Safety Steps

Before touching any files or settings, do this:

1. Create a Complete Backup

Even if your site is down, you can still backup files:

Via cPanel:

  • Login to cPanel
  • File Manager → Select public_html folder
  • Click “Compress” → Create .zip file
  • Download the .zip file to your computer

Via FTP:

  • Connect using FileZilla
  • Download entire WordPress directory
  • Save to local computer

Via SSH:

# Create backup of WordPress files
cd /var/www/
tar -czf wordpress-backup-$(date +%Y%m%d).tar.gz html/

# Create backup of database (if accessible)
mysqldump -u your_db_user -p your_db_name > database-backup-$(date +%Y%m%d).sql

2. Check If It’s Actually a Database Error

Sometimes other errors look similar. Test this:

Create a test-db.php file in your WordPress root directory:

<?php
$test_connection = mysqli_connect('localhost', 'your_db_user', 'your_db_password', 'your_db_name');

if (!$test_connection) {
    die('Connection failed: ' . mysqli_connect_error());
} else {
    echo 'Database connection successful!';
}

mysqli_close($test_connection);
?>

Upload this file, then visit: yourdomain.com/test-db.php

  • If it shows “Database connection successful!” → Your credentials work, problem is elsewhere
  • If it shows “Connection failed” → Credentials are wrong or server is down

Important: Delete test-db.php after testing (security risk to leave it).

3. Document Everything

Before making changes, write down:

  • Current database name
  • Current database username
  • Current database host
  • Hosting provider
  • Recent changes (plugin updates, migrations, hosting changes)

This helps you troubleshoot and revert changes if needed.

Solution 1: Fix wp-config.php Database Credentials

This is the most common cause — incorrect database information in your wp-config.php file.

Why This Happens

  • Hosting provider changed database details
  • Manual typo when editing wp-config.php
  • Database username/password was reset
  • Site was migrated to new server
  • Someone edited the file incorrectly

Step-by-Step Fix

Step 1: Access Your WordPress Files

You need FTP access or cPanel File Manager:

Using FileZilla (FTP):

  1. Open FileZilla
  2. Enter your FTP credentials (get from hosting provider)
  3. Connect to server
  4. Navigate to public_html or your WordPress root folder

Using cPanel File Manager:

  1. Login to cPanel
  2. Click “File Manager”
  3. Navigate to public_html folder

Step 2: Find and Download wp-config.php

  • Locate wp-config.php in your WordPress root directory
  • Right-click → Download (save backup copy to your computer)
  • Right-click → Edit (or open with text editor)

Step 3: Locate the Database Configuration Section

Look for these lines (usually around line 20-30):

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'database_name_here' );

/** MySQL database username */
define( 'DB_USER', 'username_here' );

/** MySQL database password */
define( 'DB_PASSWORD', 'password_here' );

/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

Step 4: Find Your Correct Database Credentials

For cPanel Users:

  1. cPanel → MySQL Databases
  2. Look for “Current Databases” section → Note the database name
  3. Scroll to “Current Users” → Note the username
  4. Password: You can’t view it, but you can create a new one:
    • Click “Change Password” next to the user
    • Generate strong password (save it somewhere secure)
    • Copy the new password

For VPS/Server Users:

Check your database details in your server config or run:

# Connect to MySQL
mysql -u root -p

# Once logged in, run:
SELECT user, host FROM mysql.user WHERE user LIKE 'wp_%';

# Show all databases
SHOW DATABASES;

Step 5: Update wp-config.php with Correct Credentials

Replace the placeholder values with your actual credentials:

define( 'DB_NAME', 'yoursite_wpdatabase' );     // Your actual database name
define( 'DB_USER', 'yoursite_wpuser' );         // Your actual database username
define( 'DB_PASSWORD', 'your-secure-password' );// Your actual database password
define( 'DB_HOST', 'localhost' );               // Usually 'localhost', sometimes an IP

Important Notes:

  • Remove any extra spaces before or after values
  • Keep the single quotes ' '
  • Make sure there’s a semicolon ; at the end of each line
  • Password is case-sensitive
  • Database name and username are case-sensitive on Linux servers

Step 6: Check Database Host

DB_HOST is usually localhost, but not always:

Common alternatives:

  • localhost (most shared hosting)
  • 127.0.0.1 (IP address for localhost)
  • localhost:3306 (with port number)
  • mysql.yourdomain.com (some hosts use separate MySQL server)
  • Specific IP address like 192.168.1.100

How to find your correct DB_HOST:

Check your hosting provider’s documentation, or:

cPanel users:

  • cPanel home → “MySQL Databases”
  • Look for “Database Host” or “MySQL Server”
  • Usually shows as localhost

Contact hosting support if you’re unsure — they can tell you immediately.

Step 7: Save and Upload

  1. Save the wp-config.php file
  2. Upload back to server (overwrite existing file)
  3. Set correct permissions: 644 (most hosting) or 640 (more secure)

Setting permissions via FTP:

  • Right-click wp-config.php → File Permissions
  • Enter 644 or 640
  • Click OK

Setting permissions via SSH:

chmod 644 wp-config.php

Step 8: Test Your Site

Visit your domain. If you see your site instead of the error — you fixed it!

If you still see the error, move to Solution 2.

Common Mistakes to Avoid

Leaving extra spaces: define( 'DB_NAME', ' database_name ' ); ← Those spaces break it
Correct: define( 'DB_NAME', 'database_name' );

Using wrong quotes: define( "DB_NAME", "database_name" ); ← Double quotes can cause issues
Correct: define( 'DB_NAME', 'database_name' ); ← Use single quotes

Missing semicolon: define( 'DB_NAME', 'database_name' ) ← Missing ;
Correct: define( 'DB_NAME', 'database_name' );

Wrong DB_HOST: Using localhost when your host uses something else
Correct: Check with your hosting provider for exact DB_HOST value

Solution 2: Verify Database User Permissions

Even with correct credentials, your database user might not have proper permissions to access the database.

Why This Happens

  • Hosting provider reset permissions during maintenance
  • You manually changed permissions in phpMyAdmin
  • Database user was removed from database
  • Security plugin restricted database access

Step-by-Step Fix

For cPanel Users:

Step 1: Access MySQL Databases

  1. Login to cPanel
  2. Find and click “MySQL Databases”

Step 2: Check User Association

  1. Scroll to “Add User To Database” section
  2. Check if your WordPress user is listed under “Current Databases”
  3. If your user is NOT associated with your database:
    • Select your database user from dropdown
    • Select your database from dropdown
    • Click “Add”

Step 3: Grant All Privileges

  1. After adding user, click “Manage User Privileges”
  2. Check “ALL PRIVILEGES” checkbox
  3. Scroll down and click “Make Changes”

For phpMyAdmin Users:

Step 1: Login to phpMyAdmin

  • Access through cPanel or directly if you have the URL
  • Login with your database credentials

Step 2: Check User Privileges

  1. Click on “User accounts” tab
  2. Find your WordPress database user
  3. Click “Edit privileges”

Step 3: Grant Required Permissions

WordPress needs these minimum permissions:

  • ✅ SELECT
  • ✅ INSERT
  • ✅ UPDATE
  • ✅ DELETE
  • ✅ CREATE
  • ✅ DROP
  • ✅ ALTER
  • ✅ INDEX

Best practice: Grant ALL PRIVILEGES for simplicity:

  1. Click “Check all”
  2. Click “Go” to save

For VPS/SSH Users:

# Connect to MySQL as root
mysql -u root -p

# Grant all privileges to WordPress user
GRANT ALL PRIVILEGES ON your_database.* TO 'your_wp_user'@'localhost';

# If using remote database server
GRANT ALL PRIVILEGES ON your_database.* TO 'your_wp_user'@'%';

# Flush privileges to apply changes
FLUSH PRIVILEGES;

# Verify grants
SHOW GRANTS FOR 'your_wp_user'@'localhost';

# Exit MySQL
EXIT;

Step 4: Test Connection

Visit your site. If permissions were the issue, your site should load now.

Creating a New Database User (If Needed)

If your user is completely broken, create a fresh one:

Via cPanel:

  1. MySQL Databases → “Add New User”
  2. Username: yoursite_wpuser
  3. Generate strong password (save it!)
  4. Click “Create User”
  5. Add user to database (Solution 2, Step 2)
  6. Update wp-config.php with new username and password

Via MySQL:

# Create new user
CREATE USER 'new_wp_user'@'localhost' IDENTIFIED BY 'strong_password_here';

# Grant privileges
GRANT ALL PRIVILEGES ON your_database.* TO 'new_wp_user'@'localhost';

# Apply changes
FLUSH PRIVILEGES;

Then update your wp-config.php with the new credentials.


Solution 3: Repair Corrupted WordPress Database

Database corruption can break the connection, especially after server crashes or improper shutdowns.

Why Databases Get Corrupted

  • Server crash or unexpected restart
  • Plugin or theme bug causing database write errors
  • Disk full error (forcing incomplete writes)
  • Hardware failure on hosting server
  • Manual database editing gone wrong

Symptoms of Database Corruption

  • Error establishing database connection (sometimes intermittent)
  • “Error 145: Table is marked as crashed”
  • Blank admin dashboard
  • Missing posts or pages
  • “Database error” when trying to publish content

Method 1: WordPress Built-in Database Repair

WordPress has a secret database repair tool.

Step 1: Enable Repair Mode

Edit your wp-config.php file and add this line before /* That's all, stop editing! Happy publishing. */:

define('WP_ALLOW_REPAIR', true);

Complete example:

define( 'DB_HOST', 'localhost' );
define( 'DB_CHARSET', 'utf8mb4' );
define( 'DB_COLLATE', '' );

// Enable database repair mode
define('WP_ALLOW_REPAIR', true);

/* That's all, stop editing! Happy publishing. */

Step 2: Access Repair Tool

Visit this URL directly in your browser:

https://yourdomain.com/wp-admin/maint/repair.php

Step 3: Run Repair

You’ll see two buttons:

  1. “Repair Database” — Attempts to fix corrupted tables
  2. “Repair and Optimize Database” — Fixes AND optimizes tables

Click “Repair and Optimize Database” for best results.

Step 4: Review Results

The tool will show results for each table:

wp_posts: OK
wp_postmeta: OK
wp_options: Table is marked as crashed and should be repaired
Repairing wp_options: OK

If you see “OK” for all tables, you’re good!

Step 5: Disable Repair Mode (CRITICAL)

After repair completes, immediately remove or comment out this line from wp-config.php:

// define('WP_ALLOW_REPAIR', true);  // Disabled after repair

Security warning: Leaving this enabled allows ANYONE to access the repair tool without authentication. Always disable it after use.

Method 2: Repair via phpMyAdmin

If WordPress repair tool doesn’t work or you can’t access it:

Step 1: Login to phpMyAdmin

  • Access via cPanel or direct URL
  • Select your WordPress database from left sidebar

Step 2: Select All Tables

  1. Click “Check All” checkbox at bottom of table list
  2. This selects all WordPress tables (wp_posts, wp_options, etc.)

Step 3: Repair Tables

  1. From “With selected:” dropdown menu
  2. Choose “Repair table”
  3. Click “Go”

Step 4: Wait for Completion

phpMyAdmin will show repair status for each table:

wp_posts: Table is already up to date
wp_postmeta: OK
wp_options: The storage engine for the table doesn't support repair

“Already up to date” and “OK” are good. Ignore “doesn’t support repair” (InnoDB tables can’t be repaired this way, but they auto-repair).

Step 5: Optimize Tables (Recommended)

While you’re here:

  1. “Check All” again
  2. “With selected:” → “Optimize table”
  3. Click “Go”

This cleans up fragmentation and can improve performance.

Method 3: Repair via SSH (Advanced)

For VPS users with command-line access:

Step 1: Check Database Status

# Login to MySQL
mysql -u root -p

# Select your database
USE your_database_name;

# Check all tables for errors
CHECK TABLE wp_posts, wp_postmeta, wp_options, wp_comments;

Output will show “OK” or “Table is marked as crashed.”

Step 2: Repair Individual Tables

# Still in MySQL shell
REPAIR TABLE wp_posts;
REPAIR TABLE wp_postmeta;
REPAIR TABLE wp_options;

# Or repair all tables at once
REPAIR TABLE wp_commentmeta, wp_comments, wp_links, wp_options, 
  wp_postmeta, wp_posts, wp_termmeta, wp_terms, 
  wp_term_relationships, wp_term_taxonomy, wp_usermeta, wp_users;

Step 3: Optimize After Repair

OPTIMIZE TABLE wp_posts;
OPTIMIZE TABLE wp_postmeta;
# ... repeat for all tables

# Exit MySQL
EXIT;

Alternative: Use mysqlcheck command:

# Check all tables in database
mysqlcheck -u your_db_user -p your_database_name

# Repair all tables
mysqlcheck -r -u your_db_user -p your_database_name

# Optimize all tables
mysqlcheck -o -u your_db_user -p your_database_name

# Do everything at once (check, repair, optimize)
mysqlcheck -cro -u your_db_user -p your_database_name

This is faster than manual table-by-table repair.

Method 4: WP-CLI Database Repair

If you have WP-CLI installed:

# Check database integrity
wp db check

# Repair database
wp db repair

# Optimize database
wp db optimize

Simple and effective.

What If Repair Fails?

If repair doesn’t work:

  1. Export database backup (even if corrupted)
   mysqldump -u your_db_user -p your_database_name > corrupted-backup.sql
  1. Try to recover specific tables using paid tools like MySQL Table Recovery or Stellar Phoenix
  2. Restore from backup if you have one (UpdraftPlus, cPanel backups, etc.)
  3. Contact hosting support — they may have server-side backups

Solution 4: Check If MySQL Server Is Running

If your credentials are correct but you still can’t connect, the MySQL server itself might be down.

Why MySQL Stops Running

  • Server ran out of memory (MySQL crashed)
  • Too many simultaneous connections exceeded limit
  • MySQL service was stopped accidentally
  • Server reboot (MySQL didn’t auto-start)
  • Resource limits hit on shared hosting

How to Check MySQL Status

For cPanel Users:

Unfortunately, cPanel doesn’t show MySQL status directly. You’ll need to:

  1. Contact hosting support via live chat/ticket
  2. Ask: “Is the MySQL server running? I’m getting database connection errors.”
  3. They can restart it for you

For VPS/Server Users (SSH Access):

Check if MySQL is running:

# For MySQL
systemctl status mysql

# For MariaDB (MySQL fork)
systemctl status mariadb

# Alternative command that works for both
service mysql status

Output interpretation:

Running:

● mysql.service - MySQL Community Server
   Loaded: loaded
   Active: active (running) since Mon 2025-01-06 10:23:15 UTC

Stopped:

● mysql.service - MySQL Community Server
   Loaded: loaded
   Active: inactive (dead)

How to Start MySQL Server

Ubuntu/Debian:

# Start MySQL
sudo systemctl start mysql

# Enable auto-start on boot
sudo systemctl enable mysql

# Verify it's running
sudo systemctl status mysql

CentOS/RHEL:

# Start MySQL
sudo systemctl start mysqld

# Enable auto-start
sudo systemctl enable mysqld

# Check status
sudo systemctl status mysqld

For MariaDB:

# Start MariaDB
sudo systemctl start mariadb

# Enable auto-start
sudo systemctl enable mariadb

# Verify status
sudo systemctl status mariadb

Alternative method (works on older systems):

# Start MySQL
sudo service mysql start

# Restart MySQL
sudo service mysql restart

# Stop MySQL
sudo service mysql stop

Checking MySQL Error Logs

If MySQL won’t start, check the error logs:

# View MySQL error log
sudo tail -n 50 /var/log/mysql/error.log

# For MariaDB
sudo tail -n 50 /var/log/mariadb/mariadb.log

# Alternative location
sudo tail -n 50 /var/log/mysqld.log

Common errors you might see:

Out of memory:

Cannot allocate memory for the buffer pool

Solution: Reduce MySQL memory usage or upgrade server RAM.

Too many connections:

Too many connections

Solution: Increase max_connections in MySQL config.

Port already in use:

Can't start server: Bind on TCP/IP port: Address already in use

Solution: Another process is using port 3306. Find and stop it:

sudo lsof -i :3306
sudo kill -9 [PID]

Restarting MySQL Safely

# Stop MySQL gracefully
sudo systemctl stop mysql

# Wait 5 seconds
sleep 5

# Start MySQL
sudo systemctl start mysql

# Check if it's running
sudo systemctl status mysql

Increasing MySQL Connection Limits

If MySQL keeps crashing due to connection limits:

Edit MySQL configuration:

# Edit config file
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

# Or for MariaDB
sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Find and modify these settings:

[mysqld]
max_connections = 500        # Increase from default (151)
wait_timeout = 300           # Seconds before closing idle connection
max_connect_errors = 1000    # Allow more failed connection attempts

Save file and restart MySQL:

sudo systemctl restart mysql

Docker/Coolify Users

If you’re running MySQL in Docker:

# Check if MySQL container is running
docker ps | grep mysql

# If not running, check all containers
docker ps -a | grep mysql

# Start MySQL container
docker start mysql-container-name

# View MySQL container logs
docker logs mysql-container-name

# Restart MySQL container
docker restart mysql-container-name

For Coolify users:

  • Go to Coolify dashboard
  • Navigate to your database service
  • Check status (should show green/running)
  • Click “Restart” if needed
  • Check logs for errors

Solution 5: Check Database Host (localhost vs IP Address)

Sometimes the issue is that WordPress is trying to connect to the wrong server address.

Understanding DB_HOST

DB_HOST in wp-config.php tells WordPress where to find your MySQL server. Most commonly it’s localhost, but not always.

Common DB_HOST Values

Hosting TypeTypical DB_HOSTExampleShared HostinglocalhostlocalhostSome Shared HostsCustom hostnamemysql.yourdomain.comVPS (same server)localhost or 127.0.0.1127.0.0.1VPS (with port)localhost:3306localhost:3306Remote DatabaseIP address or hostname192.168.1.50 or db.example.comDocker/CoolifyService namemysql or mariadb

How to Find Your Correct DB_HOST

Method 1: Check PHP Info

Create a file called phpinfo.php in your WordPress root:

<?php
phpinfo();
?>

Visit yourdomain.com/phpinfo.php and search (Ctrl+F) for “MYSQLI_DEFAULT_HOST” — that’s your database host.

Delete phpinfo.php after checking (security risk).

Method 2: Ask Your Hosting Provider

Contact support and ask: “What should I use for DB_HOST in wp-config.php?”

They’ll tell you immediately.

Method 3: Check cPanel (if available)

cPanel → MySQL Databases → Look for “Database Host” field near the top.

Method 4: Try Common Alternatives

If localhost doesn’t work, try these one by one in wp-config.php:

// Try these in order:
define( 'DB_HOST', 'localhost' );
define( 'DB_HOST', '127.0.0.1' );
define( 'DB_HOST', 'localhost:3306' );
define( 'DB_HOST', '127.0.0.1:3306' );

Test your site after each change.

Special Cases

Cloudways Users:

define( 'DB_HOST', 'localhost:/var/run/mysqld/mysqld.sock' );

Kinsta Users: Check your MyKinsta dashboard → Database access → MySQL hostname

GoDaddy Managed WordPress: Usually localhost, but check via hosting dashboard.

Docker/Coolify Setup:

If WordPress and MySQL are in separate containers:

// Use the service name from docker-compose.yml
define( 'DB_HOST', 'mysql' );  // or 'mariadb', 'db', etc.

// Or use container IP (not recommended, changes on restart)
define( 'DB_HOST', '172.18.0.2' );

Find Docker container name:

# List running containers
docker ps

# Check docker-compose.yml for service name
cat docker-compose.yml | grep -A 5 "mysql"

Testing DB_HOST Connection

Use this test script (save as test-host.php):

<?php
$hosts_to_test = ['localhost', '127.0.0.1', 'localhost:3306', '127.0.0.1:3306'];

foreach ($hosts_to_test as $host) {
    echo "Testing: $host ... ";
    $connection = @mysqli_connect($host, 'your_db_user', 'your_db_password', 'your_db_name');
    
    if ($connection) {
        echo "SUCCESS!\n<br>";
        mysqli_close($connection);
        break;
    } else {
        echo "FAILED: " . mysqli_connect_error() . "\n<br>";
    }
}
?>

Replace credentials and upload. Visit yourdomain.com/test-host.php — it’ll show which host works.

Delete test-host.php after testing.

Solution 6: Restore Database from Backup

If nothing else works, restoring from a recent backup is your best option.

Before Restoring

Critical: Only restore if you’re certain your current database is broken beyond repair. Restoration overwrites all current data.

Where to Find Backups

1. Hosting Provider Backups

Most hosts keep automatic backups:

cPanel users:

  • cPanel → Backup Wizard → Download Database Backup
  • or cPanel → Backups → Download a MySQL Database Backup
  • Choose your WordPress database → Download .gz file

Popular hosting backup locations:

  • SiteGround: Site Tools → Backups (past 30 days)
  • Bluehost: cPanel → Backup → Download Database
  • HostGator: cPanel → Backups → Partial Backups
  • WP Engine: User Portal → Backup Points (daily for 30 days)

2. WordPress Backup Plugins

Check if you have any of these installed:

  • UpdraftPlus (Dashboard → UpdraftPlus Backups → Restore)
  • BackWPup (Dashboard → BackWPup → Backups)
  • All-in-One WP Migration
  • Duplicator

3. Cloud Storage

If your backup plugin uploaded to cloud:

  • Check your Amazon S3 bucket
  • Check Google Drive backup folder
  • Check Dropbox/Apps/[Plugin Name]

4. Local Computer

Did you download any backups? Check your Downloads folder for .sql, .sql.gz, or .zip files.

How to Restore Database via phpMyAdmin

Step 1: Download Your Backup File

Get your .sql or .sql.gz backup file ready on your computer.

Step 2: Access phpMyAdmin

  • Via cPanel: Click “phpMyAdmin”
  • Via direct URL: Usually yourdomain.com/phpmyadmin (ask host for exact URL)

Step 3: Select Database

Click your WordPress database name in the left sidebar (e.g., yourdomain_wp123).

Step 4: Drop Existing Tables (CAUTION)

You need to remove corrupted tables first:

  1. Click “Check All” at bottom
  2. “With selected:” dropdown → “Drop”
  3. Confirm deletion (yes, this is scary but necessary)

Note: Your posts are not gone yet — they’re in the backup you’re about to restore.

Step 5: Import Backup

  1. Click “Import” tab at top
  2. Click “Choose File” button
  3. Select your backup .sql or .sql.gz file
  4. Scroll down, click “Go”

Step 6: Wait for Import

  • Small databases (< 50MB): 10-30 seconds
  • Large databases (> 100MB): 2-5 minutes
  • Don’t close the browser window

Success message:

Import has been successfully finished, X queries executed.

Step 7: Test Your Site

Visit your domain. Your site should be back online, restored to the point when the backup was created.

Restore via SSH (Advanced)

Faster for large databases:

Step 1: Upload Backup to Server

# Via SCP from local computer
scp database-backup.sql user@yourserver.com:/home/user/

# Or download from cloud
wget https://your-backup-url.com/database-backup.sql.gz
gunzip database-backup.sql.gz

Step 2: Drop Existing Database (CAUTION)

# Connect to MySQL
mysql -u root -p

# Inside MySQL:
DROP DATABASE your_database_name;
CREATE DATABASE your_database_name;
EXIT;

Step 3: Import Backup

# Import SQL file
mysql -u your_db_user -p your_database_name &lt; database-backup.sql

# If it's a large file, show progress:
pv database-backup.sql | mysql -u your_db_user -p your_database_name

# If you don't have pv installed:
sudo apt-get install pv

Step 4: Verify Import

# Connect to MySQL
mysql -u root -p

# Check tables exist
USE your_database_name;
SHOW TABLES;

# Should show wp_posts, wp_options, etc.

EXIT;

Restore via WP-CLI

If WP-CLI is installed:

# Import database from SQL file
wp db import database-backup.sql

# Alternative: Directly from backup plugin
wp updraftplus restore [backup_id]

Restore via UpdraftPlus Plugin

If you can access your dashboard (maybe wp-admin works but frontend doesn’t):

  1. Dashboard → UpdraftPlus Backups
  2. Find your backup (sorted by date)
  3. Click “Restore” next to the backup
  4. Check “Database” checkbox only (don’t restore plugins/themes if they’re working)
  5. Click “Restore”
  6. Wait 2-10 minutes depending on database size
  7. Click “Return to UpdraftPlus” when done

What If You Have No Backups?

If you truly have no backups:

  1. Contact hosting support — They often have server-level backups not visible to you
  1. Try database repair tools even if repair failed earlier:
    • MySQL Recovery Toolbox (paid software)
    • Stellar Phoenix MySQL Database Repair (paid)
    • IBBackup/XtraBackup (if you have binary logs)
  2. Check if you exported content via WordPress:
    • Dashboard → Tools → Export creates WXR file
    • Contains posts, pages, comments (but not settings/plugins)
    • Can import into fresh WordPress install
  3. Use Archive.org Wayback Machine:
    • Visit web.archive.org
    • Enter your domain
    • Copy content manually from archived versions
    • Not ideal, but better than nothing
  4. Hire a professional:
    • Database recovery specialists
    • WordPress emergency support services
    • Costs $100-500 but may save your site

After Restoration: Update Site URLs

If you restored from a backup made on a different domain or migrated sites:

Update site URLs via SQL:

-- Connect to database
mysql -u your_db_user -p your_database_name

-- Update URLs (replace with your actual domain)
UPDATE wp_options SET option_value = 'https://yourdomain.com' 
WHERE option_name = 'siteurl' OR option_name = 'home';

-- Exit
EXIT;

Or via wp-config.php (temporary override):

define('WP_HOME','https://yourdomain.com');
define('WP_SITEURL','https://yourdomain.com');

Solution 7: Advanced Server Troubleshooting (VPS/Dedicated)

For VPS users who’ve tried everything else and still have the error.

Check Server Resource Usage

Memory exhaustion can prevent MySQL from accepting connections.

# Check current memory usage
free -h

# Output:
#               total        used        free
# Mem:           2.0G        1.8G        200M
# Swap:          1.0G        800M        200M

If “free” is very low (< 100MB), MySQL may not have enough RAM.

Check which processes use the most memory:

# Show top memory-consuming processes
ps aux --sort=-%mem | head -n 10

# Real-time monitoring
htop

If MySQL is using excessive memory:

# Check MySQL memory settings
mysql -u root -p -e "SHOW VARIABLES LIKE '%buffer%';"

# Reduce memory usage by editing config
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Optimize memory settings for low-RAM servers:

[mysqld]
innodb_buffer_pool_size = 128M    # Default is often too high
key_buffer_size = 16M
max_connections = 100              # Reduce from default
table_open_cache = 64

Restart MySQL after changes:

sudo systemctl restart mysql

Check Disk Space

MySQL needs disk space to write data and temporary files.

# Check disk usage
df -h

# Output:
# Filesystem      Size  Used Avail Use% Mounted on
# /dev/vda1        40G   38G  2.0G  95% /

If disk is > 90% full, MySQL may fail. See my guide on fixing WordPress disk full errors.

Quick cleanup:

# Remove old logs
sudo journalctl --vacuum-time=7d

# Clean apt cache (Ubuntu/Debian)
sudo apt-get clean

# Find large files
sudo find / -type f -size +100M -exec ls -lh {} \;

Check MySQL Connection Limits

Too many connections can block new ones.

# Check current connections
mysql -u root -p -e "SHOW PROCESSLIST;"

# Check max_connections setting
mysql -u root -p -e "SHOW VARIABLES LIKE 'max_connections';"

# Check current active connections
mysql -u root -p -e "SHOW STATUS LIKE 'Threads_connected';"

If you’re hitting the limit, increase it:

# Edit MySQL config
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

# Add or modify:
[mysqld]
max_connections = 500

# Restart MySQL
sudo systemctl restart mysql

Check Firewall Rules

Firewall might block MySQL port 3306.

# Check if port 3306 is listening
sudo netstat -tlnp | grep 3306

# Output should show:
# tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      1234/mysqld

# Check UFW firewall status (Ubuntu)
sudo ufw status

# If MySQL needs external access, allow port
sudo ufw allow 3306/tcp

Note: For security, MySQL should only listen on localhost unless you’re using a remote database.

Check SELinux (CentOS/RHEL)

SELinux can block MySQL connections.

# Check if SELinux is enforcing
getenforce

# Temporarily disable to test
sudo setenforce 0

# Test your WordPress site - does it work now?

# If yes, you need to configure SELinux properly:
sudo setsebool -P httpd_can_network_connect_db 1

# Re-enable SELinux
sudo setenforce 1

Verify MySQL Socket File

MySQL uses a socket file for local connections. If it’s missing or in the wrong location:

# Find where MySQL socket file should be
mysql -u root -p -e "SHOW VARIABLES LIKE 'socket';"

# Output shows path, commonly:
# /var/run/mysqld/mysqld.sock
# or /tmp/mysql.sock

# Check if file exists
ls -la /var/run/mysqld/mysqld.sock

# If missing, MySQL isn't running properly
sudo systemctl restart mysql

If WordPress can’t find the socket, update DB_HOST:

// In wp-config.php, specify socket path:
define( 'DB_HOST', 'localhost:/var/run/mysqld/mysqld.sock' );

Check MySQL Error Log

The error log reveals what’s wrong with MySQL:

# View last 50 lines of MySQL error log
sudo tail -n 50 /var/log/mysql/error.log

# For MariaDB
sudo tail -n 50 /var/log/mariadb/mariadb.log

# Watch log in real-time while testing
sudo tail -f /var/log/mysql/error.log

Common errors and fixes:

“Table ‘./wordpress/wp_options’ is marked as crashed”

  • Run: wp db repair or use phpMyAdmin repair

“Can’t connect to MySQL server on ‘localhost’ (111)”

  • MySQL isn’t running: sudo systemctl start mysql

“Access denied for user ‘wp_user’@’localhost'”

  • Wrong credentials in wp-config.php

“Too many connections”

  • Increase max_connections in MySQL config

Test MySQL Connection from Command Line

# Try connecting with WordPress credentials
mysql -u your_wp_user -p -h localhost your_database_name

# If this WORKS, your credentials are correct
# Problem is elsewhere (permissions, PHP config)

# If this FAILS, you'll see exact error message
# Example: "Access denied" = wrong password

Check PHP MySQL Extension

WordPress needs PHP’s MySQL extension to connect.

# Check if mysqli extension is loaded
php -m | grep -i mysql

# Should show:
# mysqli
# mysqlnd

# If missing, install it:
sudo apt-get install php-mysql

# For specific PHP version:
sudo apt-get install php8.1-mysql

# Restart web server
sudo systemctl restart apache2
# or
sudo systemctl restart nginx
sudo systemctl restart php8.1-fpm

Docker/Coolify Specific Troubleshooting

Check if containers can communicate:

# List networks
docker network ls

# Inspect network
docker network inspect your_network_name

# WordPress and MySQL should be on same network

# Test connection from WordPress container to MySQL
docker exec -it wordpress_container_name sh
# Inside container:
ping mysql
telnet mysql 3306

Check environment variables:

# View WordPress container environment
docker exec wordpress_container_name env | grep DB_

# Should match your database credentials

Check Coolify logs:

# In Coolify dashboard, view logs for:
# - WordPress application
# - MySQL service
# Look for connection errors

Preventing Future Database Connection Errors

After fixing the error, implement these preventative measures.

1. Set Up Automated Backups

Use UpdraftPlus (my recommendation):

  1. Install UpdraftPlus from WordPress plugin repository
  2. Settings → UpdraftPlus Backups → Settings tab
  3. Choose remote storage (Google Drive, Dropbox, S3)
  4. Schedule: Daily backups at 3 AM
  5. Retention: Keep 7 daily, 4 weekly backups
  6. Files to backup: Check all boxes
  7. Database: Check “Include your database”
  8. Click “Save Changes”

Test your backup:

  • Click “Backup Now” button
  • Wait for completion
  • Download backup to verify

Cost: Free plugin + cloud storage ($0-5/month)

2. Monitor Database Health

Install Query Monitor plugin:

  1. Shows database query errors in admin bar
  2. Alerts you to slow queries
  3. Identifies problematic plugins

Check database size regularly:

# Via WP-CLI
wp db size --human-readable

# Via MySQL
mysql -u root -p -e "SELECT table_schema AS 'Database', 
  ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)' 
  FROM information_schema.tables 
  GROUP BY table_schema;"

Set up database optimization schedule:

  • Install WP-Optimize
  • Enable weekly automatic cleanup
  • Schedule: Sunday 3 AM
  • Check: Post revisions, expired transients, spam comments

3. Monitor Server Resources (VPS Users)

Install monitoring tools:

Netdata (my choice for ceeveeglobal.com):

  • Real-time resource monitoring
  • Alerts when disk/memory/CPU high
  • Shows MySQL performance metrics

Setup guide: Check Coolify monitoring documentation

Set alerts for:

  • Disk usage > 80%
  • Memory usage > 85%
  • MySQL connection errors
  • Server downtime

4. Keep Credentials Secure

Never:

  • Share wp-config.php publicly
  • Commit wp-config.php to GitHub
  • Use weak database passwords

Best practices:

  • Use strong passwords (20+ characters, mixed case, numbers, symbols)
  • Different password for each site
  • Store in password manager (1Password, Bitwarden)
  • Change passwords after team member leaves

5. Test Before Major Changes

Before updating WordPress, plugins, or themes:

  1. Create backup
  2. Test on staging site if possible
  3. Update one thing at a time
  4. Verify site works after each update
  5. If error occurs, you know what caused it

6. Use Database Connection Error Monitoring

Install Uptime Robot (free):

  1. Sign up at uptimerobot.com
  2. Add your website URL
  3. Check every 5 minutes
  4. Get email/SMS alerts if site goes down
  5. Helps you catch errors before users complain

7. Regular Maintenance Checklist

Weekly:

  • Check site loads properly
  • Review error logs for warnings
  • Verify backups completed successfully

Monthly:

  • Update WordPress core, plugins, themes
  • Check disk space usage
  • Review database size
  • Test backup restoration (important!)

Quarterly:

  • Full database optimization
  • Audit installed plugins (remove unused)
  • Review security audit logs
  • Test disaster recovery process

Common Mistakes to Avoid

Mistake 1: Editing wp-config.php Without Backup

Why it fails:

  • One typo breaks entire site
  • No way to recover if you don’t remember what you changed
  • Can make problem worse

Real consequence: User added extra space in DB_NAME, broke site, couldn’t remember original database name, spent 3 hours troubleshooting.

Correct approach:

  • Always download original wp-config.php before editing
  • Make changes in text editor, review carefully
  • Upload and test
  • Keep backup for 30 days

Mistake 2: Using Wrong Quote Types in wp-config.php

Why it fails:

// ❌ WRONG - Curly/smart quotes break PHP
define( "DB_NAME", "database_name" );

// ❌ WRONG - Mix of quote types
define( 'DB_USER', "username" );

// ✅ CORRECT - Straight single quotes
define( 'DB_NAME', 'database_name' );

How it happens: Copying from Word, email, or some websites converts quotes to “smart quotes.”

Correct approach:

  • Only edit in plain text editor (Notepad++, VS Code, Sublime)
  • Never edit in Microsoft Word or Google Docs
  • If copying from email, paste into text editor first to strip formatting

Mistake 3: Repairing Database Without Backup

Why it fails:

  • Repair tools can delete data if tables severely corrupted
  • Plugin bugs can target wrong tables
  • No recovery option if repair goes wrong

Real example: User ran “DELETE FROM wp_posts WHERE post_type=’revision'” but made typo — deleted all posts instead of revisions. No backup = total data loss.

Correct approach:

  • Export database via phpMyAdmin before any repair
  • Download .sql file to computer
  • Verify file size is reasonable (> 100KB for typical site)
  • Then proceed with repairs

Mistake 4: Leaving Database Repair Mode Enabled

Why it fails:

define('WP_ALLOW_REPAIR', true);

This line allows anyone to access yourdomain.com/wp-admin/maint/repair.php without login.

Security risk:

  • Attackers can run repair repeatedly (DOS attack)
  • They can see your database table structure
  • May crash site by overloading repair operations

Correct approach:

  • Add line, run repair immediately
  • Remove line as soon as repair completes
  • Never leave enabled permanently

Mistake 5: Assuming “Inactive” Means “Deleted”

Why it fails:

  • Deactivating plugin stops it from running
  • But doesn’t remove files or database tables
  • Orphaned tables can cause connection issues if corrupted

Correct approach:

  • Deactivate plugin first (test site still works)
  • If not needed, click “Delete” (not just deactivate)
  • Use Advanced Database Cleaner to find orphaned tables
  • Remove orphaned data after confirming plugin deleted

Mistake 6: Testing Production Instead of Staging

Why it fails:

  • Testing database credentials on live site means visitors see errors
  • Repeated connection attempts can trigger host security
  • Failed repair attempts can corrupt database further

Correct approach:

  • Use staging site for testing if available
  • Enable maintenance mode during repairs:
  define('WP_MAINTENANCE', true);
  • Test fixes during low-traffic hours (2-4 AM)

Mistake 7: Not Checking ALL Credentials

Why it fails:

Many people check DB_NAME but forget:

  • DB_USER (database username is different from database name)
  • DB_PASSWORD (case-sensitive)
  • DB_HOST (not always localhost)

All four must be exactly correct.

Correct approach:

  • Create checklist and verify each value individually
  • Copy-paste from hosting panel (don’t manually type)
  • Use test-connection.php script to verify before editing wp-config.php

Conclusion

The “Error Establishing a Database Connection” looks scary, but it’s usually a quick fix once you identify the cause.

Here’s your action plan based on hosting type:

For Shared Hosting Users:

  1. Check wp-config.php credentials (Solution 1) → 15 minutes
  2. Verify database user permissions (Solution 2) → 10 minutes
  3. Run database repair tool (Solution 3) → 15 minutes
  4. Contact hosting support if none work → They check MySQL status

Total time: 30-60 minutes for most cases

For VPS/Server Users:

  1. Run SSH diagnostics (Solution 7) → 20 minutes
  2. Check if MySQL is running (Solution 4) → 5 minutes
  3. Verify wp-config.php credentials (Solution 1) → 10 minutes
  4. Repair database if needed (Solution 3) → 15 minutes
  5. Set up monitoring to prevent recurrence → 30 minutes

Total time: 1-2 hours including prevention setup

My Experience

When ceeveeglobal.com had this error last year, it was Solution 1 — a single extra space in DB_NAME broke everything. I spent 2 hours troubleshooting before noticing: define( 'DB_NAME', ' mysite_wp ' ); instead of define( 'DB_NAME', 'mysite_wp' );.

Since then, I’ve implemented:

  • Automated daily backups to Backblaze B2
  • Netdata monitoring with alerts at 80% resource usage
  • Weekly database optimization via WP-Optimize
  • Staging site for testing updates

Haven’t had the error since.

Need Help?

Drop a comment below with:

  • Your hosting type (shared/VPS)
  • Which solution you tried
  • Error messages you’re seeing

I respond to every comment and can help troubleshoot your specific situation.

 

Frequently Asked Questions

Q1: Will I lose my content with this error?

Answer:
No, your content is still in the database. This error means WordPress can’t access the database, not that the database is deleted. Your posts, pages, and media files are intact.

However, take immediate action because:

  • Visitors can’t see your site
  • Search engines may deindex pages if down for days
  • You can’t create new content or approve comments

Create a backup immediately, even with the error active.

Q2: Can I fix this without technical knowledge?

Answer:
Yes! Solutions 1 and 2 are beginner-friendly:

  • Solution 1: Check database credentials in wp-config.php (15 minutes)
  • Solution 2: Verify user permissions in cPanel (10 minutes)

Both use graphical interfaces (cPanel, FileZilla) with no command-line required.

If those don’t work, contact your hosting support — they’ll check if MySQL is running and can restart it for you.

Q3: How do I know which solution to try first?

Follow this decision tree:

  1. Start with Solution 1 (wp-config.php credentials) — Fixes 70% of cases
  2. If credentials are correct → Solution 2 (user permissions) — Fixes 15% of remaining cases
  3. If still broken → Solution 3 (database repair) — Fixes 10% of remaining cases
  4. If still broken → Solution 4 (MySQL server status) — For VPS users
  5. Last resort → Solution 6 (restore backup)

Most people fix the issue with Solutions 1-3.

Q4: My wp-admin shows the error but the homepage works fine. What’s happening?

Answer:
This happens when:

  • Your homepage uses caching (cached version displays)
  • Admin area requires database connection (can’t cache dynamic queries)

Visit your site in incognito mode or after clearing cache. If you still see homepage, your caching plugin is masking the error.

Fix it now — visitors will eventually see the error when cache expires or when viewing non-cached pages.

Q5: Can a plugin cause this error?

Answer:
Indirectly, yes. Plugins can:

  • Corrupt database tables (triggers connection errors during queries)
  • Overload database with queries (exhaust connection limits)
  • Incorrectly modify wp-config.php (break credentials)

To test if a plugin is the cause:

  1. Access server via FTP or File Manager
  2. Rename /wp-content/plugins/ folder to /wp-content/plugins-disabled/
  3. Try loading your site
  4. If it works, one plugin was the culprit
  5. Rename back to /plugins/, then disable plugins one by one to find the bad one

Q6: I just migrated to a new host and got this error. What’s wrong?

Answer:
After migration, your old database credentials no longer work. Update wp-config.php with new host’s credentials:

  1. Login to new host’s cPanel
  2. Find MySQL Databases section
  3. Note: Database name, database username, database host
  4. Create new password for database user
  5. Update wp-config.php with these new values
  6. Upload to new server

Also update site URLs if domain changed (see Solution 6 restoration section).

Q7: Should I use localhost or 127.0.0.1 for DB_HOST?

Answer:
Try localhost first — it works for 95% of hosting setups.

Technical difference:

  • localhost → MySQL checks for socket file first, then TCP connection
  • 127.0.0.1 → Forces TCP connection only

Some hosts require 127.0.0.1 if socket file is misconfigured.

If neither works, ask your host for the exact DB_HOST value.

Q8: Can too many visitors cause database connection errors?

Answer:
Yes, if your site exceeds the max_connections limit:

Shared hosting: Usually 25-50 simultaneous connections (very limiting)
VPS: Configurable, default 151 connections

Solutions:

  • Upgrade to VPS for higher limits
  • Install caching plugin (reduces database queries)
  • Optimize slow queries (Query Monitor plugin identifies them)
  • Increase max_connections in MySQL config (VPS only)

Q9: Is this error related to the “White Screen of Death”?

Answer:
They’re different errors but can appear together:

  • Database Connection Error: Can’t reach database server
  • White Screen of Death: PHP fatal error (often caused by memory limit, broken plugin, or corrupted file)

If you see a completely blank page (no error message), that’s White Screen. Check my guide on fixing WordPress White Screen of Death.

Q10: My host says everything is fine on their end. What now?

Answer:
If hosting confirms MySQL is running and credentials are correct:

  1. Check wp-config.php locally – download and inspect for issues:
    • Extra spaces in credentials
    • Wrong quote types (" vs ')
    • Missing semicolons
    • Incorrect DB_HOST value
  2. Try different DB_HOST values:

php

   define( 'DB_HOST', 'localhost' );
   define( 'DB_HOST', '127.0.0.1' );
   define( 'DB_HOST', 'localhost:3306' );
  1. Test connection from server (ask host to run this):

bash

   mysql -u your_db_user -p -h localhost your_database_name

If this works but WordPress doesn’t connect, problem is in wp-config.php syntax.

Related WordPress Errors You Might Encounter

After fixing database connection errors, you might see related issues:

“WordPress Database Error: Disk Full”

Cause: Server storage reached 100% capacity, MySQL can’t write data
Related: Can trigger database connection errors if MySQL crashes
Internal link: How to Fix WordPress Database Disk Full Error

“WordPress Memory Limit Exhausted”

Cause: PHP memory limit too low for database operations
Related: Large database queries can exceed memory during connection
Internal link: How to Fix WordPress Memory Size Exhausted

“HTTP Error 500 Internal Server Error”

Cause: Various causes including database issues, .htaccess problems
Related: Can occur simultaneously with database connection errors
Internal link: Fixing HTTP Error 500 in WordPress

“White Screen of Death”

Cause: PHP fatal errors preventing page rendering
Related: Can be caused by failed database connections
Internal link: How to Fix WordPress White Screen of Death

“503 Service Unavailable Error”

Cause: Server temporarily unable to handle requests
Related: MySQL overload can trigger 503 errors
Internal link: Understanding and Fixing 503 Service Unavailable

 

Tools & Resources

Essential Plugins

  • UpdraftPlus – Cloud backup solution (free)
  • WP-Optimize – Database cleanup and optimization
  • Query Monitor – Database query debugging
  • Advanced Database Cleaner – Remove orphaned tables

Hosting Recommendations

  • Contabo VPS – Affordable VPS I use for ceeveeglobal.com
  • DigitalOcean – Premium VPS with excellent documentation
  • SiteGround – Best managed WordPress hosting
  • Hostinger – Budget-friendly shared hosting

Backup Storage

  • Backblaze B2 – Most affordable at $0.005/GB/month
  • Amazon S3 – Most reliable, $0.023/GB/month
  • Google Drive – Free 15GB tier for small sites
  • Dropbox – $12/month for 2TB

Development Tools

  • FileZilla – Free FTP client for file access
  • WP-CLI – WordPress command-line interface
  • PuTTY (Windows) / Terminal (Mac/Linux) – SSH access
  • phpMyAdmin – Web-based database management

Monitoring Tools

  • Netdata – Real-time server performance monitoring
  • Uptime Robot – Free uptime monitoring (checks every 5 min)
  • Coolify – Self-hosted application deployment platform
  • ManageWP – WordPress management dashboard

    Leave a Reply

    Mini Chatbot

    Wait a moment

    AI Chatbot
    Offline