Sometimes you may face issue with your WordPress blog with error message “Error establishing a database connection”. This will make your site unavailable for you and users. You can’t access your WordPress admin dashboard. This can be the frustrating time to you. This tutorial will guide you step by step to find out the cause and fix it.
1. Check MySQL Server
First, check if MySQL server is up and running. You can use below command to connect your MySQL server. This will insure that your database server is running properly.
$ mysql -u <username> -p
If you don’t have command access, connect database with phpMyAdmin or Adminer.
2. Check WordPress Config File
The next step is to verify connection settings in the wp-config.php configuration file. Edit file and check following settings.
define('DB_NAME', 'wordpress'); define('DB_USER', 'wpuser'); define('DB_PASSWORD', 'wppassword'); define('DB_HOST', 'localhost');
Make sure all above entries are configured correctly. You can simply verify these settings by connecting MySQL server using above details either from command line or phpMyAdmin.
$ mysql -h localhost -u wpuser -p'wppassword' wordpress
The above command should be connected to MySQL server properly. You can also verify all tables by running show tables commands from MySQL shell.
3. Check Database Connection
At the end, You can verify all settings by create a small php script. create a new file dbconn.php and add following content.
<?php $DB_HOST = "localhost"; $DB_USER = "wpuser"; $DB_PASSWORD = "wppassword"; $conn = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
Upload dbconn.php to the server under WordPress document root and access it through web browser. If there is any issue with the connection to MySQL using PHP with configured settings, You will see the error message on the web page.