Oct 16, 2011

Error establishing a database connection - WordPress

When I imported production database and configured code on my local dev machine, I got this error even I had updated wp-config.php with correct information. I fixed the problem after some changes. This article explains troubleshooting steps to fix this error.


1. First, Make sure, MySql is running. Open PhpMyAdmin and connect the database.

2. Check User has sufficient permission to connect database. For this, Create a test page say testconnection.php, put following code and run it.


<?php
$link = mysql_connect('localhost', 'root', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?> 

3. If above code is working fine then Open wp-config.php, Make sure you have defined correct information, No additional spaces/tabs in following parameters:

DB_NAME

DB_USER

DB_PASSWORD

DB_HOST

4. For Wordpress Multisite:

Suppose you have to configure wordpress in Xampp> htdocs > techbrij folder. The final URL would be

http://localhost/techbrij

then check DOMAIN_CURRENT_SITE, PATH_CURRENT_SITE and $base parameters in wp-config file.

DOMAIN_CURRENT_SITE: localhost(your dev server)

PATH_CURRENT_SITE: /techbrij/(your dev folder)

If It's okay then open database and check wp_blogs and wp_site tables have correct domain name and path.

5. Open wp_options table and check HOME and SITEURL parameters, See here to configure production URL to dev URL.

6. Still getting error, turn off Multisite functionality in wp-config if exists and test.

define( 'MULTISITE', false);

7. Open admin side of Wordpress and check whether it is connected or not. If it is connected means problem is related to plugin. Disable cache plugin or other one by one and test it.

Hope, It helps. If you have any other step or opinion to fix this, share it in below comment box.