How to Resolve "Error Establishing a Database Connection" on Apache/Nginx
What Causes "Error Establishing a Database Connection"?
This error means your web application (WordPress, Laravel, custom PHP, etc.) successfully received an HTTP request but could not open a socket to the database server. The three most common causes are: wrong database credentials in the config file, the MySQL/MariaDB service has crashed or stopped, or the database itself has a corrupted table that prevents connections from completing authentication.
Quick Diagnostic Table
| Scenario | Cause | Fix |
|---|---|---|
| Error on all pages | MySQL service stopped | sudo systemctl restart mysql |
| Error after password change | Wrong DB credentials in config | Update wp-config.php / .env |
| Error on specific site only | Wrong DB_HOST or DB_NAME | Verify config file values |
| Error after server crash | Corrupted InnoDB tables | Run mysqlcheck --repair |
| Too many connections error | MySQL max_connections hit | Increase max_connections in my.cnf |
How to Fix the Database Connection Error
Fix 1 — Verify Database Credentials
Open your config file and cross-check every value:
- WordPress:
/var/www/html/wp-config.php— check DB_NAME, DB_USER, DB_PASSWORD, DB_HOST - Laravel:
.envfile — check DB_HOST, DB_DATABASE, DB_USERNAME, DB_PASSWORD
DB_HOST is almost always localhost or 127.0.0.1 unless your DB is on a remote server.
Fix 2 — Check and Restart MySQL
- Check status:
sudo systemctl status mysql - If inactive:
sudo systemctl start mysql - If it fails to start, check:
sudo journalctl -u mysql -n 50
Fix 3 — Test the Connection via CLI
Run this command to test your credentials directly: mysql -u your_db_user -p -h localhost your_db_name. If this fails with "Access denied," your password is wrong. If it shows "Can't connect to server," MySQL is not running.
Fix 4 — Repair Corrupted Tables
Run the MySQL repair utility: sudo mysqlcheck --repair --all-databases -u root -p. This fixes InnoDB and MyISAM table corruption that commonly occurs after unclean server shutdowns.
Fix 5 — Check MySQL Error Log
Inspect /var/log/mysql/error.log for the root cause. Look for InnoDB corruption messages, out-of-disk-space errors, or authentication plugin failures. Address the specific error found.
Verification
✓ How to Confirm the Fix Worked
Reload the website. For WordPress, the "Error Establishing a Database Connection" banner will be replaced by your site. For Laravel, run php artisan migrate:status — a successful DB connection will list your migrations. Monitor MySQL uptime with mysqladmin -u root -p status.