Beginner's Guide for WordPress / Start your WordPress Blog in minutes

How to Fix the Error Establishing a Database Connection in WordPress

Are you seeing the ‘Error establishing a database connection’ notice on your WordPress website? It is a fatal error that makes your WordPress website inaccessible to the users.

This error occurs when WordPress is unable to make a connection to the database. A number of things can affect your WordPress database connection which makes it a bit difficult for beginners to troubleshoot.

In this article, we will show you how to easily fix the error establishing a database connection in WordPress.

Fixing the database connection error in WordPress

What Causes Error Establishing a Database Connection in WordPress?

The ‘Error establishing a database connection’ issue can be caused by incorrect database information in your WordPress settings, corrupt database, or an irresponsive database server.

Database connection error in WordPress

A database is a software which makes it easy to store, organize, and retrieve data into other software.

As a content management system, WordPress uses a database to store all your content and other website data. It then connects to the database each time someone visits your website.

WordPress needs the following information for connecting to the database:

  • Database name
  • Database username
  • Database password
  • Database server

This information is stored in your WordPress configuration file called wp-config.php.

If any of these items are incorrect, WordPress would fail to connect to your database server, and you’ll see the ‘Error establishing a database connection’ error.

It is one of the most common WordPress errors. Apart from incorrect credentials, this error can also appear if the database server is down, or the database files are corrupt.

Let’s take a look at how to fix error establishing database connection issue in WordPress with step by step troubleshooting.

Video Tutorial

Subscribe to WPBeginner

If you’d prefer written instructions, just keep reading.

1. Check Your WordPress Database Credentials

The most common reason for database connection error in WordPress is incorrect database credentials. If you have recently moved your WordPress site to a new host, then this could be the most likely reason.

Your WordPress database credentials are stored in the wp-config.php file. It is the WordPress configuration file that contains important WordPress settings including database information.

If you have not edited wp-config.php file before, then take a look at our guide on how to edit wp-config.php file in WordPress.

You’ll be looking for the following lines in the wp-config.php file.

// ** 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' );

You need to make sure that the information for the database name, username, password, and database host is correct.

You can confirm this information from your WordPress hosting account dashboard. Simply log in to your hosting account and click on MySQL databases under the database section.

We’re using Bluehost dashboard in our screenshot, but the process will be similar in other hosting control panels.

Database information

This will take you to the database management page in your hosting dashboad. From here, you can find out your database name and the username.

Database name and username

Below that you will find the database users and links to change the user password.

Changing database user password

Once you have confirmed your database name, username, and password, you can change that information in your wp-config.php file if needed.

After that, try visiting your website again to see if the database connection error has gone.

If you can still see the error, then this means that something else is wrong. Continue reading for more troubleshooting steps.

2. Check Your Database Host Information

If you are confident that your database name, username, and password information is correct, then you may want to make sure that you are using the correct database host information.

Most WordPress hosting companies use localhost as your database host. However, some managed WordPress hosting companies use separate servers to host databases. In that case, your database host information will not be localhost.

You need to contact your WordPress hosting company to confirm your database host information.

3. Repair WordPress Database

If you are getting a different error on the wp-admin, for instance, something like “One or more database tables are unavailable. The database may need to be repaired”, then you need to repair your database.

You can do this by adding the following line in your wp-config.php file. Make sure to add it just before ‘That’s all, stop editing! Happy blogging’ line wp-config.php.

define('WP_ALLOW_REPAIR', true);

Once you have done that, you can see the settings by visiting this page: http://www.yoursite.com/wp-admin/maint/repair.php

Repair WordPress database

Note: the user does not need to be logged in to access the database repair page. Once you are done repairing and optimizing your database, make sure to remove this code from your wp-config.php.

4. Check if Your Database Server is Down

If everything seems to be correct, and WordPress still cannot connect to the database, then your database server (MySQL server) may be down.

This could happen due to heavy traffic on a server. Basically, your host server just cannot handle the load (especially when you are on shared hosting).

Your site will get really slow and for some users it may even output the error. So the best thing you should do is get on the phone or live chat with your hosting provider and ask them if your MySQL server is responsive.

If you have other websites running on the same server, then you can check those sites to confirm that your SQL server is down.

If you do not have any other site on the same hosting account, then simply go to your hosting dashboard and try to access phpMyAdmin and connect the database.

If you can connect, then we need to verify if your database user has sufficient permission. Create a new file called testconnection.php and paste the following code in it:

<?php
$link = mysqli_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($link);
?>

Make sure to replace the username and password. You can now upload this file to your website and access it via web browser.

If the script connected successfully, then it means that your user has sufficient permission, and there is something else that is wrong.

Go back to your wp-config file to make sure that everything there is correct (re-scan for typos).

Other Solutions That Have Worked for Users

If the above-mentioned troubleshooting tips failed to fix the database connection error on your website, then you may try these additional steps.

Reported by our users, these steps have helped some users resolve the database connection error on their websites.

1. Update WordPress Site URL

Try updating the WordPress site URL using phpMyAdmin. Simply access phpMyAdmin from your hosting account dashboard, and select your WordPress database.

Running SQL in phpMyAdmin

After that click on the SQL menu on the top and enter the following MySQL query.

UPDATE wp_options SET option_value='YOUR_SITE_URL' WHERE option_name='siteurl'

Don’t forget to provide your own site URL and change wp_options to your own table name as you may have changed the WordPress table prefix.

2. Rebooting Web Server

Users on dedicated servers, local server, and virtual private servers (VPS) can try rebooting their servers.

This will restart your web and database server which may fix some temporary glitches causing the error.

3. Ask for help

If everything else fails, then you may need to contact your web hosting company. All good WordPress hosting companies will help you troubleshoot the problem, point you in the right direction, or even fix it for you.

You can also hire WordPress developers from Codeable that can help you fix this issue for reasonable rates. The best part is that these developers are highly-vetted by Codeable team, so you know they can be trusted.

We hope this article helped you fix the error establishing a database connection in WordPress. You may also want to see our WordPress troubleshooting guide for tips on resolving WordPress issues on your own.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit – a collection of WordPress related products and resources that every professional should have!

Reader Interactions

648 CommentsLeave a Reply

    • You’re so helpful! All my writing was saved! Yes, I need to do a backup… I did one! Thanks so much, this is just the resource I needed. Luckily Google pulled it right up.

  1. I have a test wordpress installation on my home computer running on fedora. I moved/reinstalled the computer with a recent copy of fedora. I restored the database and the wordpress installation. Everything should have been fine except I had the “cannot connect to the database” error. I have had this wordpress installation for a long time. Turns out that when I moved to the new server I also got a new my.cnf. Now I checked it and made everything the same but for some reason i did not add the following line in /etc/my.cnf. Maybe i just wanted to see what would happen. hmmm…what does this button do…..
    # Default to using old password format for compatibility with mysql 3.x
    # clients (those using the mysqlclient10 compatibility package).
    old_passwords=1
    After I added that line, the database connection problem was fixed.
    So I need to drop that user and recreate it with the new password format.
    Note I also have
    skip-networking
    in /etc/my.cnf and….it works. That keeps mysql off the network, including 127.0.0.1. It’s just one less entry point for the mischief-makers.

  2. I had a database-connection-error on a client’s site and could access the database via PHPMyAdmin but running the testconnect.php file suggested above came up with a response unlisted in this article:

    “PHP Warning: mysql_connect(): No connection could be made because the target machine actively refused it.”

    I got in touch with Fasthosts who my clients were with and it turned out that they had issues integrating PHP5.4 “and the only fix is to reset the MySQL database user password.”

    So if you’re in that boat, then you may be able to fix it by accessing the database via PHPMyAdmin and running the query:

    SET SESSION old_passwords = 0;
    SET PASSWORD = PASSWORD(‘databasepasswordgoeshere’);

    !! IMPORTANT NOTE !! : make sure you get ‘databasepasswordgoeshere’ correct otherwise you’ll be resetting your db password to something new rather than the same password and it could break your site even further!

  3. I must be really dumb! i understand a little of wordpress but this all sounds way out of my leage.

    I have tried to do exactly what you have said and this is what I get

    Warning: Cannot modify header information – headers already sent by (output started at /customers/8/a/3/chigwelltkd.com/httpd.www/wordpress/wp-config.php:2) in /customers/8/a/3/chigwelltkd.com/httpd.www/wordpress/wp-includes/functions.php on line 2801
    Error establishing a database connection.

    I have no idea what to do next!!!

    Not only have i lost the site from the web but I know cannot get in to wordpress admin.

    IS THERE ANY HOPE!!!!!

  4. Thanks so much for writing this post, it saved me quite a bit of time and a lot of headaches. Cheers!

  5. Solved my issue in less than 10mins cause of this article
    YOUR ARE DOPE…you mean business

    Thanks a mil!!!

  6. Hi,

    Recently i uploaded a theme to the wordpress site, i have also uploaded the local database. I have modified my wp-config file too. Still i am getting error database connection error. When i opened my wp-admin it redirecting to wp-login.

    Can i know what might be the problem?

    • We think its normal behavior for wordpress to redirect you to wp-login.php when you try to access wp-admin directory. Can you please explain further? have you checked your wp-config.php file? does it have your live site’s database information?

      Admin

  7. I had 4 sites give a 127.0.0.1 “Cannot connect to server” message & I also had no access to admin. I went through troubleshooting, & nothing helped. So, I contacted my web-hosting service, Bluehost, to inquire whether the MySQL server was responsive. The tech told me to login to my control panel’s File Manager, select “Show hidden files,” and then to go inside my root directory for each domain & rename my .htaccess file to .htaccess.old . He said he guessed that a plugin added code to my .htaccess file, causing my wp-admin to redirect to an IP address. It worked. :)

  8. Just got this error on my own website. wp-config.php was allright. PhpMyAdmin could load the database. When trying to open the wp_options table PhpMyAdmin said the table must be repaired. Using the repair function in PhpMyAdmin fixed the table, reporting one row had been removed (not saying which one). No clue as to what caused this.
    Thanks for the article, helped me debug the error.

  9. Just got this problem, checked db through host cPanel and admin user seems to have been removed from database assuming that is why wp cannot connect. Problem is my ftp also seems to have been knocked out so i am unable to apply any solutions! sub-domain seems to still be working. It’s difficult to imagine this as being anything other than malicious!

  10. I just got this problem with one of my sites and fixing the database from wp-config.php did not work. I fixed it by upgrading to WordPress 3.6.1 in cPanel (Softaculous).

  11. Today, for some reason my site is facing the database connection issue.
    • Confirmed my database access is working via testconnection.php.
    • Changed the salt keys with new ones.
    • Defined the proper site URLs to ‘WP_HOME’ and ‘WP_SITEURL’
    • No issue with server slowness as my other websites in other root directories are working.

    I’m guessing it may be a plugin recently added?
    How do you properly uninstall a plugin if you can’t pull up both wordpress root and wp-admin directories in the browser?

    Thanks in advanced.

  12. Thanks a lot for such a good article!
    My problem was a bit different. I had this issue because of ‘clicky analytics’ plugin.
    I almost went mad as i didnt have any idea of what the problem could be. Finally after lot of trial and error i figured out that it was a plugin interference.

  13. Huh! sir you deserve an award.
    It just worked for me. I was having this problem from last one month and you just served with this.
    Thank you very much :)

  14. Problem occured when requesting new password and didn’t realise this was going to create a db problem. Fortunately I found your comments and guidelines. Problem solved in 3 minutes.
    Thanks again (now I’ve subscribed to your weekly email)

  15. My problem happened when I moved the site to a new hosting. I’d altered the config file to match my new database, username & password. But nothing worked.

    Your tip about checking the WP-admin page did the trick. It told me something was wrong with the username. I went into c-panel and realized I hadn’t tied the user to the database. Two seconds later, all was good!

    You potentially saved me hours of testing the wrong things! Thanks!

  16. I want to give you a big kiss.

    VERY useful.

    However, my issue seemed a little odd – and it might help someone else:

    This morning our domain produced error:

    Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 30720 bytes) in /home/gurumaga/public_html/wp-admin/includes/class-wp-list-table.php on line 384

    I tried to increase PHP memory allocation.

    Added to wp-settings (in root folder):
    define(‘WP_MAX_MEMORY_LIMIT’, ‘256M’);
    resulted in:
    ‘Error establishing a database connection’

    Removed line and added lower limit:
    define(‘WP_MEMORY_LIMIT’, ’64M’);
    resulted in:
    ‘Error establishing a database connection’

    Removed all changes in wp-settings.php now as original.
    ‘Error establishing a database connection’ persisted (for 5 – 10 mins)

    Before reverting to the original error:
    Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 30720 bytes) in /home/gurumaga/public_html/wp-admin/includes/class-wp-list-table.php on line 384

    I increased the PHP memory limit to: define(‘WP_MEMORY_LIMIT’, ’64M’); again
    Then ran the database repair as you advised.

    Although no database errors were identified, the site is now back up and running.

    Odd – I’m not sure if you or anyone else can make sense of it??

  17. Embarrassed… I tried everything in this blog and was double checking everything…
    It never occurred to me that I’d typo’ed when entering the password.

    Doh! So, here’s a +! for double checking the basics ;)

  18. Hi, I made the mistake of changing the home url, initially it was http://shaneynayguns.com/wordpress and the site url was: http://shaneynayguns.com/wordpress too. I then changed the site url to http://shaneynayguns.com (thinking that that will make my site go live, as you can tell I’m an absolute idiot at this). Nothing happened, so genius here, changed the home url to shaneynayguns.com. That’s when things start to go awry: I couldn’t log in to wp-admin anymore and going to .com/wordpress redirects me to an error page. (shaneynayguns.com remain unchanged and directs to a landing page) I then went on to a forum and followed the exact instructions which were:
    1. go to phpmyadmin
    2. go to the correct database
    3. browse wp_option
    4. edit site url (I changed it to .com/wordpress)
    Apparently based on everyone’s comments, it worked for all of them… except me! shaneynayguns.com/wordpress now redirects to a page with “error establishing a database connection”! It’s driving me mental! I was hoping if any of you could help me with this. As is obvious, I have not a clue when it comes to web jargon so I would really appreciate a simplified solution. Yes I’m an idiot, and I terribly need help! (F.Y.I: I host on godaddy)
    Thanks in advance!

      • Hey, this worked for me. My wordpress website is on Godaddy and i was trying to put inside of subdirectory. now it works. Just after this, show up some database upgrade screen then everything is fine. also, i took out these defines above and still working. thanks.

  19. Thanks heaps for your info guide, helped me fix my problem.
    To let you know my resolve, I could not see a typo in the wp-config.php but decided to delete my Database and linked Username. I then created new ones and manually updated the new data into the wp-config and boom straight in. One thing to note is the database and username were originally the same name, so not sure if that was an issue as its a new site.

  20. My website is down and I keep getting “Error establishing database connection” message.
    I checked my WP-Config.php page and it looks fine on the inside, but when I preview it, the page says this

    Warning: require_once(reddoorplayhouse.com/open/wp-settings.php) [function.require-once]: failed to open stream: No such file or directory in /hermes/waloraweb096/b619/moo.reddoor1/wp-config.php on line 95

    Fatal error: require_once() [function.require]: Failed opening required ‘reddoorplayhouse.com/open/wp-settings.php’ (include_path=’.:/usr/local/lib/php-5.2.17/lib/php’) in /hermes/waloraweb096/b619/moo.reddoor1/wp-config.php on line 95

    What does that mean. And what can I do? Thanks for your help.

  21. This is a frustrating problem that has been happening multiple times to a few of my sites over the past few weeks. I can fix it easily enough by replacing the Unique Keys and Salts in my wp-config.php file (grabbing new ones at: https://api.wordpress.org/secret-key/1.1/salt), but then days later I have to replace them again… so while I can fix the symptom, I’m still trying to determine why this keeps happening at http://brioagency.com

  22. Hi

    Just thought I’d thank you for helping me fix a site.

    Changing localhost to the database IP address fixed my issue.

    Thanks

    Andrew

  23. I had made copies of the files and saved them on the server.

    So when today the database connection error occured, I relaized, I had changed user, , pwd, database access but nothing worked.

    So renamed the current wp-config.php as wp-configold.php
    and copied the wp-config.php from the archive and pasted as wp-config.php.

    Voila it works.

  24. Forgot that the database is “local” to the application. I used the site URL by mistake. Switched DB_HOST to ‘localhost’ and all is golden.

    Thanks for the blog! +1

  25. You know sometimes you just find the perfect resource and it answers all your questions. I tip people for pouring me a cup of coffee. I wish it was super easy to just put a buck or two in the wpbeginner tip jar right now, but I guess a thanks will have to do.

    • Thanks Ben. Its always our pleasure to help. The best way to thank us is by spreading kind words about our site or by simply sharing this article on twitter, facebook, etc :)

      Admin

  26. WP Beginner is just awesome & so is Syed! I don’t know how many times my search results have let me to your site and each time, I’ve learned something really helpful, useful, & practical.

    This time, with my database connection error issue, I just had to clear my browser’s cache. FML Anyways, that was the advice that I got after contacting my host. It seems to have worked & hopefully that’s all it takes! How to prevent it from happening again is above me.

  27. All I have to say: “THANK YOU!” :-) your post fixed my issues and spared me a couple of hours of work.

  28. For me the issue was solved by properly setting “siteurl” and “home” in wp_options table did the trick for me, I could log into my admin and change everything!

    One day I’ll buy you a cookie!!

  29. I have a big problem… i did not set the site up and do not have axxess to the php or any files. i was trying to add pages and the next time i visited the site there was the error. Do i need to get to the admin initiator etc, is there no other way into the site?

  30. I get this error intermittently. Perhaps I don’t have enough resources on my amazon ec2 free tier instance. I’ve had the problem 3 times in the last week but have been able to solve it each time by restarting the database server.
    Thanks for the post

    • Thank you so much, Udumbuke. This was exactly the step I forgot in moving my site to a new host. I’m so glad I can stop headaching over this! And great guide altogether on this site.

  31. This error happened to me because I wanted to back up my database and could not remember the password. I changed the password in GoDaddy – but this didn’t change it in the wp-config.php! Once I changed it in wp-config, everything worked okay again.

    THANK YOU FOR SUCH A COMPREHENSIVE SOLUTION!!! And a truly useful site. Kudos!

  32. In step review of wp-config.php you have to consider the user name and password that is there in the file, the user may not exist in the database (mysql), the password has changed so check if there is the user. In case the user does not exist in the database create it, assign the password found in wp-config.php and provide permits for administration of the database (DBA).

    This happened to me to restore my wordpress.

    • Thanks dude! Restored my database and all i needed to do then was reassign the correct user with the correct database in cpanel.

  33. Hi guys, thanks for this info.
    Helped me to fix a problem with a WordPress site I created.
    It had been happily running for over a month when it started having the “Error Establishing a Database Connection” error.

    Finally fixed it by changing DB_HOST to use the full host name rather than the ‘localhost’ that had been in there before.

    I don’t know why it worked initially and then stopped working. But its working now…
    Cheers,
    Pat Walsh

    • Having the same connection to DB problem, and after reading comments, I decided to change the wp.config file refrence to my actual host to localhost and for some reason that fixed it. So my solution was the opposite to the one above. Just a shot in the dark…

  34. it is indeed helpful for me as i m facing this problem currently… thanks for this great article..

  35. I’m getting this issue temporary at my site just for few seconds.
    how can I be free from this?
    Please help!

      • Thank you,
        I already upgrade my hosting plan from basic to Pro.
        But still same as before.
        I using Adminimize, AG Custom Admin, Akismet, BuddyPress Template Pack, Display widgets, Fast Secure Contact Form, Google XML Sitemaps, Jetpack by WordPress.com, Page Views Count, Polldaddy Polls & Ratings, User Switching, Better WP Security, BuddyPress, Hotfix, W3 Total Cache, wordPress Importer and WordPress SEO.
        Which one is making problem??
        Have you any Idea?

  36. If you have all the info in the config file correct and is still having the problem, check to see if you have any spam prevention plugin active such as Fail2Ban. I found that it was causing the database problem. I believe it happens cause when you’re editing the wordpress via wp-admin, you make too many sequence requests to the apache it triggers the Fail2Ban service for www-data user. Try uninstalling Fail2Ban or any other spam controller. Then, restart both mysql server and apache to get hid of the Error message.

    I hope this helps.
    b

Leave a Reply to alin Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.