Error establishing a database connection wordpress multisite

When attempting to convert WordPress to a Multisite setup, I get the error: Error establishing a database connection I'm using WordPress 3.7.1 on Windows 7 with a WAMP server. wp-config.php ...

When attempting to convert WordPress to a Multisite setup, I get the error:

Error establishing a database connection

I’m using WordPress 3.7.1 on Windows 7 with a WAMP server.

wp-config.php

define('WP_ALLOW_MULTISITE', true ); 
define('SUBDOMAIN_INSTALL', false); 
define('DOMAIN_CURRENT_SITE', 'localhost');
define('PATH_CURRENT_SITE', '/wordpress_test4/');
define('SITE_ID_CURRENT_SITE', 1); 
define('BLOG_ID_CURRENT_SITE', 1);

.htaccess

RewriteEngine On 
RewriteBase /wordpress_test4/ 
RewriteRule ^index.php$ - [L]

# add a trailing slash to /wp-admin 
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR] 
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule ^ - [L] 
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] 
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*.php)$ $2 [L] 
RewriteRule . index.php [L]

Kirk Beard's user avatar

Kirk Beard

9,38612 gold badges46 silver badges47 bronze badges

asked Nov 1, 2013 at 10:18

user1987095's user avatar

9

You need to add to your wp-config.php:

define('MULTISITE', true);

I had the same problem. I skipped this line because I already had define('WP_ALLOW_MULTISITE', true); in my wp-config and it looked to me the same.

answered Jan 26, 2014 at 20:33

Dima L.'s user avatar

Dima L.Dima L.

3,30331 silver badges30 bronze badges

0

Had same problem, found 3 possible solutions:

  1. Make sure: DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST in your wp-config.php are really the ones expectected.

  2. As Dima L. mentioned before, define('MULTISITE', true); is expected too.

  3. But what solved it for me* is etting up multi-site for WordPress, changed the wp_blogs table’s column path to an undefined location for my website. I changed it to / and the DB connection was re-established.

Giacomo1968's user avatar

Giacomo1968

25.4k11 gold badges70 silver badges100 bronze badges

answered Feb 22, 2014 at 20:03

Sabin Chirila's user avatar

2

I struggled a long time because of this issue. And finally found a solution.

You should not add all those settings at once in the wp-config.php file. Follow the exact steps described here: http://codex.wordpress.org/Create_A_Network

Only add the following code as the first step:

/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );

And then refresh your page.
After that, in your administration panel go to Tools -> Network Setup and choose your sub-site settings.

For the rest, just use the instructions from the link above.

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Jun 3, 2016 at 21:45

Sorin Haidau's user avatar

1

I had a strange encounter very recently. After setting up a dev server which runs under a different domain and moving a multisite setup to it I got the same error “Error establishing a database connection”. I had checked that all the wp_options tables have the correct domains in the respective settings and that my database connection had the right credentials and would work under normal circumferences.

I found a way to get a better error reporting. I added an output of the database object in the function dead_db() in functions.php which then showed me that it couldn’t find any blogs for my site in the table wp_blogs. I simply forgot to update the domains for the test server in this table.

function dead_db() {
  global $wpdb;
  
  echo "<pre>";
  print_r($wpdb);
  echo "</pre>";
  
  wp_load_translations_early();

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Aug 25, 2016 at 0:59

Torsten McFly's user avatar

2

My DOMAIN_CURRENT_SITE in wp-config.php was define('DOMAIN_CURRENT_SITE', 'www.example.com');

Removing http:// in wp_blogs -> domain fixed my issue.

Giacomo1968's user avatar

Giacomo1968

25.4k11 gold badges70 silver badges100 bronze badges

answered May 14, 2016 at 20:48

irandoust's user avatar

irandoustirandoust

5325 silver badges12 bronze badges

I added $base = ‘/’; into the config, which solved the issue.

define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', 'mydomain.com');
$base = '/';
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

Pang's user avatar

Pang

9,344146 gold badges85 silver badges121 bronze badges

answered Dec 25, 2014 at 7:49

D.A.H's user avatar

D.A.HD.A.H

8502 gold badges9 silver badges19 bronze badges

1

If you have taken an entire database dump of a multisite, you would have to change the domain name to match your localhost domain on the following tables:

  1. wp_blogs [update the domain fields]
  2. wp_options [siteurl and home]
  3. wp_site [domain field]

For a multisite, defining WP_HOME and WP_SITEURL on the config.php will not work.

Ideally before importing the DB dump, if you have the .sql file, you could do a search and replace of all the domains to your own localhost domain.

These above steps worked for me.

answered Jul 15, 2021 at 18:33

sydadder's user avatar

sydaddersydadder

3151 silver badge15 bronze badges

Besides to all said above, if working with multisite environment please check also the following:
in the respective subdirectories (/home/subsitename) there exist separate wp-config.php and .htaccess files for each of (sub)sites, so the above mentioned parameters have to be adjusted in all of these files.
For example, my main site was working correctly since these files in my /home directory were OK, but when tried to access my sub-sites, I’ve been receiving database connection error message until I adjusted these files too.

answered Nov 8, 2014 at 11:54

azvonko's user avatar

Inspired by Sabin’s answer, I checked wp_blogs and found that the domain value was still pointing to the wrong domain (I was moving a multi-site to a dev server). Running UPDATE wp_blogs SET domain='example.com'; fixed my issue (note that I’m using subfolder multisite, not subdomain — don’t blindly run that SQL!)

answered Aug 6, 2015 at 17:51

Jon G - Megaphone Tech's user avatar

If you’re running WHM/cPanel and you’ve already checked that you’ve added the MULTISITE/WP_ALLOW_MULTISITE constant, you’re probably running into virtual host issues.

If you’re getting the database error, chances are, your name servers or A record is correct. Otherwise your domain wouldn’t be pointing to your server with a database connection. But, you’ve probably forgotten, or missed, the domain name from the cPanel aliases.

Just head to cPanel, search for ‘Aliases’ and type in the domain name you’re missing under ‘Create a New Alias’.

You can also get to cPanel by logging into WHM, searching for ‘List Accounts’, searching for the account you want and clicking on the CP icon.

answered Nov 8, 2017 at 23:05

Oliver Tappin's user avatar

Oliver TappinOliver Tappin

2,4711 gold badge23 silver badges42 bronze badges

I had the problem after moving the multisite from a sub directory to the root directory.

What solved it for me was partly what has been mentioned by Sabin Chirila :

  1. Make sure: DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST in your wp-config.php are really the ones expectected.
  2. As Dima L. mentioned before, define(‘MULTISITE’, true); is expected too.
  3. Change the ‘wp_blogs’ table’s column ‘path’ to «/» and the DB connection was re-established.

but I had to change some more things.

  1. In order to be able to view the frontend I also had to change the ‘wp_site’ table’s column ‘path’ to «/»
  2. and then (in theme twentyseventeen-child) I had to reconfigure some configuration settings in the backend as they weren’t taken into account. But that was simple as the data was still there.

Ouroborus's user avatar

Ouroborus

15.6k3 gold badges37 silver badges60 bronze badges

answered Aug 26, 2017 at 19:38

para's user avatar

parapara

212 bronze badges

1

Here’s How I fixed it

config settings

define( 'MULTISITE', true );
define( 'SUBDOMAIN_INSTALL', false );
define( 'DOMAIN_CURRENT_SITE', 'localhost' );
define( 'PATH_CURRENT_SITE', '/myblog/' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );

then in the database table (found using phpmyadmin) wp_blogs set the values for your root blog (which should be lie/number 1) to

domain localhost
root /myblog/

And finally — reset the sitrurl and homepage in options table (again found using phpmyadmin) to

 http://localhost/myblog/

answered Feb 24, 2014 at 12:49

JorgeLuisBorges's user avatar

JorgeLuisBorgesJorgeLuisBorges

5083 gold badges8 silver badges21 bronze badges

If you are encountering a WordPress error message or white screen, don’t panic. Someone has likely encountered the same message before and it can easily be solved.

This page lists the most common WordPress errors experienced by WordPress users, and provides a starting point for fixing them. At WordPress Support, you will also find links to more detailed pages or forums where a volunteer will be there to help.

The White Screen of Death

Both PHP errors and database errors can manifest as a white screen, a blank screen with no information, commonly known in the WordPress community as the WordPress White Screen of Death (WSOD).

Before resorting to desperate measures, there are a number of reasons for the WordPress white screen of death:

  • A Plugin is causing compatibility issues. If you can access the Administration Screens try deactivating all of your Plugins and then reactivating them one by one. If you are unable to access your Screens, log in to your website via FTP. Locate the folder wp-content/plugins and rename the Plugin folder plugins_old. This will deactivate all of your Plugins. You can read more about manually deactivating your plugins in the Troubleshooting FAQ.
  • Your Theme may be causing the problem. This is especially likely if you are experiencing the white screen of death after you have just activated a new Theme, or created a New Site in a WordPress Network. Log in to the WordPress Administration Screens and activate a default WordPress Theme (e.g. Twenty Twenty-One). If you are using WordPress 5.8 and below, please switch to Twenty Twenty-One theme since the Twenty Twenty-Two theme requires 5.9 and above. If you can’t access your Administration Screens, access your website via FTP and navigate to the /wp-content/themes/ folder. Rename the folder for the active Theme.

The WP_DEBUG feature often provides additional information.

Internal Server Error

Internal Server Error message

There can be a number of reasons for an Internal Server Error. Here are some thing you can do to solve it:

  • The most likely issue is a corrupted .htaccess file. Log in to your site root using FTP and rename your .htaccess file to .htaccess_old. Try loading your site to see if this has solved your problem. If it works, make sure to visit Settings > Permalinks and reset your permalinks. This will generate a new .htaccess file for you.
  • Try deactivating all of your Plugins to see if it is a Plugin issue. If you are unable to access your WordPress Administration Screens, deactivate your Plugins via FTP by following these instructions.
  • Switch the Theme to a WordPress default Theme (e.g. Twenty Twenty-One) to eliminate any Theme-related problems. If you are using WordPress 5.8 and below, please switch to Twenty Twenty-One theme since the Twenty Twenty-Two theme requires 5.9 and above.
  • Increase the PHP Memory limit
  • Try re-uploading the wp-admin and wp-includes folders from a fresh install of WordPress.

Error Establishing Database Connection

If you get a page featuring the message “Error Establishing Database Connection,” this means that there is a problem with the connection to your database and there could be a number of reasons for this. The following are possible reasons and solutions.

Incorrect wp-config.php Information

“Error establishing a database connection” is usually caused by an error in your wp-config.php file. Access your site in your FTP client. Open up wp-config.php and ensure that the following are correct:

  • Database name
  • Database username
  • Database password
  • Database host

Learn more about editing wp-config.php.

If you are sure your configuration is correct you could try resetting your MySQL password manually.

Problems with Your Web Host

The next step is to contact your web host. The following hosting issues may be causing the problem:

  • Your database has met its quota and has been shut down.
  • The server is down.

Contact your hosting provider to see if either of these issues is causing your problem.

Compromised Website

If you have checked wp-config.php for errors, and confirmed with your host for hosting issues, it is possible that your site has been hacked.

Scan your site with Sucuri SiteCheck to ensure that it hasn’t been compromised. If it has you should check out My Site was Hacked.

Failed Auto-Upgrade

There will be situations when the WordPress auto-update feature fails. Symptoms include:

  • A blank white screen and no information.
  • A warning that the update failed.
  • A PHP error message.

The WordPress automatic upgrade feature may fail due to a glitch in the connection with the main WordPress files, a problem with your Internet connection during upgrade, or incorrect File Permissions

To update your WordPress site manually, see the Manual Update article.

Connection Timed Out

The connection timed out error appears when your website is trying to do more than your server can manage. It is particularly common on shared hosting where your memory limit is restricted. Here are some things you can try:

  • Deactivate all Plugins. If deactivating all the WordPress Plugins on your site resolves the issue, reactivate them one-by-one to see which plugin is causing the problem. If you are unable to access your Administration Screens, read about how to manually deactivate your plugins.
  • Switch to a default WordPress Theme. If you are using WordPress 5.8 and below, please switch to Twenty Twenty-One theme since the Twenty Twenty-Two theme requires 5.9 and above. This should rule out any Theme-related problems.
  • Increase your memory limit in wp-config.php. If you are on shared hosting you may have to ask your hosting provider to increase your memory limit for you.
  • Increase the maximum execution time in your php.ini file. This is not a WordPress core file so if you are not sure how to edit it, contact your hosting provider to ask them to increase your maximum execution time. See below instructions for increasing maximum execution time.

Maintenance Mode Following Upgrade

When WordPress updates, it automatically installs a .maintenance file. Following upgrade, you may receive a message that says “Briefly unavailable for scheduled maintenance. Please check back in a minute.” The maintenance file may not have been removed properly.

To remove this message do the following:

  1. Log in to your website using your FTP program
  2. Delete the .maintenance file, which will be found in your site root.

Read more about the maintenance mode issue.

You Make Changes and Nothing Happens

If you are making changes to your website and you do not see the changes in your browser, you may need to clear your browser cache. Your browser stores information about the websites that you visit. This makes it faster to load websites when you visit them because the browser just has to reload information already stored on your computer, rather than downloading it again.

If you make a change to a website and the browser does not think it is significant, it will simply load the data from your cache, and you won’t see your changes. To fix the problem, simply empty your browser cache or close the tab and reopen the link.

Pretty Permalinks 404 and Images not Working

If you are experiencing 404 errors with pretty permalinks and a white screen when you upload images, mod_rewrite may not be enabled in Apache by default. Mod_rewrite is an extension module of the Apache web server software which allows for “rewriting” of URLs on-the-fly. It’s what you need to make pretty permalinks work.

WordPress Multisite networks usually experience this but it can also occur on shared hosting providers or after a site migration or server move.

Reset your permalinks through Settings > Permalinks. If this does not work, you may have to edit the .htaccess file manually.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

If you are not familiar with editing your .htaccess file, contact your hosting provider to ask them to turn on mod_rewrite rules. There is more information on pretty permalinks in the WordPress Codex.

Custom Post Type 404 Errors

You may experience problems with 404 errors and custom post types. Try the following steps:

  1. Make sure that none of your Custom Post Types and single pages have the same name. If they do, rename the single page, including the slug.
  2. Log in to your WordPress Administration Screens, navigate to Settings > Permalinks. Select the default permalinks. Save. Then reselect your preferred permalinks. This will flush the rewrite rules and should solve your problem.

Specific Error Messages

There are a number of different errors that will appear in your error logs. To access your error logs you will need to turn on debugging and then locate your error log via FTP. The following information will help you to decipher some of the common error messages.

PHP Errors

Below are some common PHP error messages.

Fatal Errors and Warnings

If you receive a warning that WordPress cannot modify header information and headers are already sent, it usually means that you have spaces or characters before the opening tags or after the closing tags. Read how to fix the headers already sent error.

If you are experiencing this problem when you have just installed WordPress you may have introduced a syntax error into wp-config.php. These instructions will help you to fix the error.

Call to undefined function

An error reading call to undefined function could mean that a WordPress Plugin is trying to find a file or data which isn’t present or accessible in the code. Reasons for this include:

  • An error when trying to auto-install or auto-upgrade a Plugin. Try installing or upgrading the Plugin manually.
  • An error when trying to auto-install or auto-upgrade a Theme. Try installing or upgrading the Theme manually.
  • You may be using an incompatible WordPress Plugin or incompatible Theme. This could happen with older versions of WordPress and a new WordPress Plugin, or if you are trying to use a WordPress Multisite Plugin on a single site installation. Upgrade WordPress to resolve this issue.
  • You may be trying to call a function that doesn’t exist. Check functions.php for misspellings.

Try deactivating the WordPress Plugin or changing the WordPress Theme that caused the error to appear. If you are unable to do this from within the Administration Screens, you may have to do this manually via FTP.

Allowed memory size exhausted

An Allowed Memory Size Exhausted error means that your WordPress installation doesn’t have enough memory to achieve what you want. You can try out the following steps:

  • Increase your memory limit in wp-config.php
  • Increase your memory limit by editing php.ini. This is not a file that comes with WordPress so if you are unfamiliar with it you should contact your web host about increasing your memory limit.
Maximum execution time exceeded

You may receive a message such as “Maximum execution time of 30 seconds exceeded” or “Maximum execution time of 60 seconds exceeded”. This means that it is taking to longer for a process to complete and it is timing out. There are a number of ways to fix this error.

Editing .htaccess

Make sure you back up .htaccess before you edit it.

Add the following line to .htaccess:

php_value max_execution_time 60

Editing php.ini

Add the following to php.ini

max_execution_time = 60

If you are unsure of how to make these changes, or if you are on shared hosting that prevents you from making them yourself, you should contact your hosting provider and ask them to increase your maximum execution time.

Parse errors

Syntax Error

A syntax error means that you have made a mistake while creating your PHP structure. You could, for example, be;

  • Missing a ; at the end of an individual line.
  • Using curly quotation marks.
  • Missing a curly bracket.

When this error appears it will tell you which file the error appears in (functions.php for example) and approximately which line (it may not always be the exact line so be sure to check just before and just after) in the code.

Unexpected

If you are receiving an error which says ‘parse error: unexpected’ this usually means that you have forgotten to include a character. The most common are:

  • Unexpected ‘=’ : you have forgotten to include the $ when referencing a variable
  • Unexpected ‘)’ : you have forgotten to include the opening bracket (
  • Unexpected ‘(‘ : you have forgotten to include the closing bracket )
  • Unexpected T_STRING: you have forgotten a quotation mark or a semi-colon at the end of the previous line
  • Unexpected T_ELSE: you have an else statement with no opening if statement

Use of an undefined constant

As with parse errors, “use of an undefined constant” means that you are missing a character. It could be one of the following:

  • Missing a $ when referencing a viariable
  • Missing quotation marks around array keys

Database Errors

The following errors may appear in relation to your WordPress database.

Error 13 – Cannot Create/Write to File

There are a number of reasons why you may be experiencing this error.

MySQL cannot create a temporary file. 

The MySQL variable tmpdir is set to a directory that cannot be written to when using PHP to access MySQL. To verify this, enter MySQL at the command line and type show variables. You’ll get a long list and one of them will read: tmpdir = /somedir/ (whatever your setting is.)

To solve this, alter the tmpdir variable to point to a writable directory.

  1. Find the my.cnf file. On *nix systems this is usually in /etc/. On Windows system, Find the my.ini.
  2. Once found, open this in a simple text editor and find the [mysqld] section.
  3. Under this section, find the tmpdir line. If this line is commented (has a # at the start), delete the # and edit the line so that it reads: tmpdir = /writable/dir where /writable/dir is a directory to which you can write. Some use /tmp, or you might also try /var/tmp or /usr/tmp. On Windows, use C:/Windows/tmp.
  4. Save the file.
  5. Shutdown MySQL by typing mysqlshutdown -u -p shutdown.
  6. Start MySQL by going to the MySQL directory and typing ./bin/safe_mysqld &. Usually the MySQL directory is in /usr/local or sometimes in /usr/ on Linux systems.

The file permissions are incorrect

Correct the File Permissions.

If none of this make sense and you have someone to administrate your system for you, show the above to them and they should be able to figure it out.

CREATE Command Denied to User

This error occurs when the user assigned to the database does not have adequate permissions to perform the action to create columns and tables in the database. You will need to log in to CPanel or Plesk to give your database user adequate permissions.

Alternatively you can create a new user to assign to your database. If you do create a new user you will need to ensure that it is updated in wp-config.php.

Error 28

It could be because:

  • you are out of space on /tmp (wherever tmpdir is), or,
  • you have too many files in /tmp (even if there is lots of free space), or,
  • Your cache on your server is full

This is a MySQL error and has nothing to do with WordPress directly; you should contact your host about it. Some users have reported that running a “repair table” command in phpMyAdmin fixed the problem.

Error 145

This indicates that a table in your database is damaged or corrupted. If you are comfortable using phpMyAdmin you can use these instructions on repairing your MySQL database tables.

Always backup your database before performing any actions on it.

If you have not used phpMyAdmin before, or are uncomfortable doing so, contact your web host and ask them to run CHECK/REPAIR on your database.

Unknown Column

An unknown column error can be caused by a missing column in the database. If you have just upgraded WordPress then try manually upgrading again. To update your WordPress site manually, see the Update article.

If you are running a database query when you encounter the error then you may by using incorrect quotation marks for the identifier quote character. This question on Stack Overflow provides more details. Also see the MySQL documentation.

Resources

  • MySQL Error Codes and Messages

When you are moving a WordPress multisite website to a different url, you may get the error “Error establishing a database connection”. Based on the error description, you will likely try to verify database connection, username and password but still you are facing the error. In fact, this error is not related to database connection issue. It is related to the url stored in your database and wp-config.php file.

Moving Multisite to localhost

I wanted to create a test environment using my current PROD site. My PROD site uses WordPress Multisite with a subdirectory (and not subdomain). Once I imported database, changed wp-config.php, created web application in IIS server and tried to access site, it gave me the above error.

I have verified database connection information multiple times thinking that there is something wrong with credentials or collation.

Error Caused by Settings And Not Database

After couple of trial and error, I figured out that this error is not caused by database connection issue but rather values stored in database and wp-config.php file.

Settings to Change

Here is what I did in order to make the site run on http://localhost/mytestsite. I needed to change wp_blogs, wp_options and wp_site tables. If your WordPress uses a table prefix other than wp, make sure you modify the correct MySQL tables.

Table: wp_blogs

This table contains list of all the blogs available on your multisite.

Change domain = ‘localhost’ and path = ‘/mytestsite/’ for the blog_id=1. Path must contains “/” at the beginning and at the end.

Table: wp_options

This table contains WordPress options. Change “siteurl” and “home” options’ option_value to “http://localhost/mytestsite/”. This must contain “/” at the end.

Table: wp_site

Change domain = ‘localhost’ and path = ‘/mytestsite/’ for the blog_id=1. Path must contains “/” at the beginning and at the end.

File: wp-config.php

Make sure that you have following constants defined.

define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'localhost');
define('PATH_CURRENT_SITE', '/mytestsite/'); // must contain "/" at the beginning and at the end
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

Once I made above mentioned changes, site worked without any issue.

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.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.

Few things are as frustrating as finding that your website is down — particularly if you rely on it for business. The Error Establishing a Database Connection message represents a serious issue and prevents all access to your site, so fixing it is a top priority. However, if you’re not familiar with how WordPress works, it can be a confusing problem.

Don’t fret. Although this error is serious, it’s also highly fixable. With a few troubleshooting steps, you can have your site back online in no time. Here’s what we’ll cover:

  • What is the Error Establishing a Database Connection?
  • Common Causes of Database Connection Errors
  • How to Fix the Error Establishing a Database Connection (4 Steps)

Let’s get started!

Got a WordPress Error? No Problem

You can skip troubleshooting if you sign up for DreamPress hosting. Our friendly WordPress experts are always standing by to solve your website problems — big or small.

Understanding the Error Establishing a Database Connection in WordPress

Before we dig too much into this particular error message, let’s have a brief lesson on how WordPress sites work. Nearly all website information — including post data, plugin settings, login credentials, and more — is stored and organized in a MySQL database.

DreamHost Glossary

MySQL

MySQL is a relational database management system that offers practical management tools. You can use MySQL to create, modify, and extract data from relational databases through the SQL programming language. It can also control the access that users have to the database.

Read More

When a visitor comes to your site, WordPress uses PHP to query the database and pull the correct information, which is then displayed as the complete page.

If, for whatever reason, WordPress can’t access your site’s database or it isn’t working properly, the result is an Error Establishing a Database Connection message.

The Error Establishing a Database Connection message on a WordPress site.

This error prevents the entire page from loading. In fact, you won’t even be able to access the WordPress dashboard (your site’s back end).

If your site uses caching, visitors may still see stored copies of your pages. Therefore, if you catch the error early and resolve the problem before your site’s cache refreshes, you can avoid too many interruptions to your site and business.

Fortunately, as WordPress errors go, a database connection error is usually pretty simple to resolve. The most common cause, by far, is just a mismatch of login credentials for the database.

Common Causes of the Error Establishing a Database Connection

There are four typical causes of the database connection error:

  • Incorrect database login credentials. Possibly the most common cause of the Error Establishing a Database Connection is simply that WordPress has incorrect login credentials for your database. This could be either the database name, username, or password. Remember, these login details are different from the ones you use to access your site.
  • Database corruption. A WordPress MySQL database contains a lot of information. If any part is deleted or corrupted, the result can be the error in question. Corruption can result from manually tinkering with the database, but it can also just happen as a consequence of normal use. Although MySQL is quite robust, nothing is perfect, and errors do occur.
  • WordPress core file corruption. Similarly, corruption can occur in the core WordPress files that make up your site. Even though these files are outside the database, they may sometimes result in the same error.
  • Problems with the web server or hosting provider. If problems arise with your host or server (if you’re self-hosting) and WordPress can’t reach it to query the database, it will throw this error. These problems can include outages, data loss, and hardware failures.

As we said, incorrect credentials are the most common cause of the error, but any of these could be the culprit. For that reason, fixing the error can involve some troubleshooting.

How to Fix the Error Establishing a Database Connection in WordPress (In 4 Steps)

Although this is a serious error, it’s fortunately fairly easy to resolve. Below, you’ll find step-by-step instructions for troubleshooting and fixing the problem. Note that you should try each step in order, only moving to the next if one doesn’t work.

Step 1: Check Your WordPress Database Credentials

Since this is the most likely cause of the error, it should also be the first step in your troubleshooting. The first thing you’ll need to do is locate the credentials WordPress is currently using to access your database.

This information is stored in your site’s wp-config.php file. You can use a Secure File Transfer Protocol (SFTP) client to access it.

Alternatively, if your site is hosted with DreamHost, you can access the file system from the DreamHost Control Panel. To do so, sign in to your control panel and navigate to Domains > Websites. Hover the mouse over the domain you’d like to fix, then click ‘manage’ to see the folder icon. Then click on the file folder symbol next to the site that’s experiencing the error.

Inside the file browser, select the folder named after your website, then open wp-config.php. Here, look for three pieces of information — the database name, username, and password. They should be near the top of the file.

The database login credentials in the wp-config.php file.

With this information in hand, head to your DreamHost Panel and navigate to More > MySQL Databases. Look for the hostname that corresponds to your website’s name. It will be formatted as mysql.yoursitename.com, with “yoursitename” being the name of your website.

If the hostname isn’t on this page, skip down to Step 2 and come back here when you’re done adding it.

In the section called Database(s) on this server, make sure the database name matches the one you pulled from wp-config.php earlier. If it does, this isn’t the problem, and you can move on to the next step.

If it doesn’t match, go back to wp-config.php and update it with the correct database name.

Next, you can find the usernames that have access to each database beside their names on the MySQL Databases page.

The usernames that have access to the database listed in the DreamHost Control Panel.

To view the password, click on the username. On the page that opens, scroll down to the Current Password field and click on Show.

The password options for a database user in the DreamHost Control Panel.

If the username or password doesn’t match your wp-config.php file, update it with the correct details. Alternatively, if the username matches but the password doesn’t, you could update the database password on the User Details screen.

Step 2: Check Your Database Host Information

If you’ve checked the database login credentials and fixed any errors, but you’re still getting the Error Establishing a Database Connection message, the next thing you should check is your database host information.

The hostname for your database can be found in wp-config.php, right alongside the database name and login credentials.

The MySQL database hostname in the wp-config.php file.

Note this information, then head back to your DreamHost Panel and navigate to More > MySQL Databases. This time, you’re looking to make sure the hostname in your wp-config.php file is listed on this page. If it’s not, you’ll need to add it.

To add a hostname, simply click on the Add New Hostname button. On the next page, enter the hostname you want to use and select the correct website domain from the dropdown.

When you’re finished, click on Create this MySQL hostname now! Note that it can take a few hours for this new hostname to propagate through the DNS, so feel free to take a break here. When some time has passed, come back and check if your site is working. If you’re still getting the database error message, proceed to the next step.

Step 3: Repair Your WordPress Database

If you’re still receiving the error message, you can try repairing the database to fix possible corruption. We recommend using the built-in WordPress database repair tool for this.

To access it, open up your wp-config.php file and add the following code at the end:

define('WP_ALLOW_REPAIR', true);

Next, open a new browser tab and navigate to https://yoursitename.com/wp-admin/maint/repair.php, replacing “yoursitename” with your website’s actual domain. This will bring up the database repair tool.

The WordPress database repair tool.

Click on Repair Database and let it do its thing. You can choose Repair and Optimize Database if you like, but it takes considerably longer. Either way, when the tool is finished, load your website again and check for the error. If it’s gone, then you’ll know a corrupted database was the cause.

However, if you’re still seeing the error message, head to the next step. Before you do, make sure to head back into wp-config.php and delete the code you added to turn on the tool. If you leave it there, someone with ill intentions could gain access to your site easily.

Step 4: Check if Your Database Server Is Down

If all the above steps have failed, one final possibility is that your database server has gone down. At this point, it’s a good idea to verify with your hosting provider that everything is working correctly.

There are a number of reasons why your database host or server might be experiencing issues:

  • Too many simultaneous connections to the database. Some providers have limits on how many connections a server can have at one time.
  • Problems with another site on your shared hosting server. If you’re on a shared hosting plan, you’re splitting resources with other sites. If one of them has problems, it can spill over to your site. This is one of the reasons dedicated or managed WordPress hosting plans can be beneficial.
  • Hardware troubles. Hardware eventually fails, and it’s possible that the server your database is stored on has done just that. Ideally, your host will have redundancies in place so that if one server goes down, there’s another copy of your data available, but this isn’t always the case — especially if you’re hosting your own database on a home or office server.

Your best bet here is to reach out to your web host and inquire about outages or other known issues. If there are none, you can report your problem and ask the support staff to look into it for you.

At DreamHost, you can always find your support options by clicking on the Support button in the top right corner of your control panel:

Support options in the DreamHost Control Panel.

DreamHost offers 24/7 support, so you can get help any time you need it.

Additional Tips and Solutions That Have Worked for Other Users

If you’ve tried all of the above tips and you’re still having trouble with the Error Establishing a Database Connection, there are a couple of other options that have worked for some users. You can try these either before or after going through the troubleshooting steps above:

  • Update your WordPress site URL. If you’ve recently moved your WordPress installation for any reason (such as moving to a new domain name or migrating to HTTPS), you may need to update your site URL in the database. You can find full instructions for doing so in our knowledge base.
  • Reboot your web server. This one might seem a little basic, but sometimes the simplest solutions are the most effective. If you host your database on your own server, try turning it off and back on. Computers are complex, and a simple reboot can fix all manner of odd problems you may be experiencing.
  • Ask for help. If you’re not comfortable doing your own troubleshooting, or you’ve tried everything and still can’t get rid of the Error Establishing a Database Connection message, there’s no shame in reaching out for help. You can get in touch with DreamHost support 24/7 by clicking the Support button in your DreamHost panel. You can also try searching on help forums such as Stack Exchange or Quora. Your question may have already been answered on one of these sites. If not, you can always ask.

At this point, you’ve hopefully resolved the issue and gotten your site back up and running.

Get Content Delivered Straight to Your Inbox

Subscribe to our blog and receive great content just like this delivered straight to your inbox.

Further Reading

Want to learn more about fixing common WordPress errors? We’ve got you covered!

  • How to Fix the 500 Internal Server Error in WordPress
  • How to Fix Syntax Errors in WordPress
  • How to Fix the WordPress Not Sending Email Issue

Ready to Fix a Database Connection Issue?

If you’ve gone to check on your website and found yourself greeted by the Error Establishing a Database Connection message, you’re not alone. It’s a common error with relatively simple fixes, so getting your site up and running again shouldn’t be too difficult.

You should follow these steps to troubleshoot a database connection error:

  1. Check your WordPress database credentials.
  2. Check your database host information.
  3. Repair your WordPress database.
  4. Check if your database server is down.

If you’d rather not have to deal with these types of problems in the future, consider upgrading to DreamPress, our managed WordPress hosting service. Then you can leave the troubleshooting to us!

Это – один из худших кошмаров для владельца веб-сайтов. Вы вводите URL-адрес вашего сайта… однако вас приветствует не ваша главная страница, а нечто другое. Вместо этого вы видите пустой экран. Вне зависимости от того, по какой ссылке вы перешли, вас встречают зловещие слова «Error establishing a database connection».

error-establishing

Чем дольше ваш сайт будет лежать, тем больше трафика вы потеряете. А это означает потерянных подписчиков, клиентов, а также упущенный доход. Однако что вообще привело к такой ошибке? Что она означает? И, что самое важное, как исправить ее, чтобы вернуть свой сайт в нормальное состояние как можно быстрее?

В этой статье мы расскажем вам, что означает это сообщение об ошибке, что может вызывать его, а также посмотрим, как найти корень зла и исправить его.

Содержание

  1. Что означает «Error Establishing a Database Connection»?
  2. Что приводит к этой ошибке?
  3. Решение проблем с «Error Establishing a Database Connection»
  4. 1. Определяем, с чем произошла ошибка.
  5. 2. Проверяем учетные данные БД в wp-config
  6. 3.Все еще появляется ошибка?

Что означает «Error Establishing a Database Connection»?

Для начала давайте посмотрим на то, как WordPress отображает ваш сайт, и тогда станет ясно, почему эта ошибка настолько разрушительная. WordPress написан на PHP и MySQL. Вся информацию, которая составляет ваш сайт, хранится в базе данных MySQL, а PHP используется в WordPress для сохранения и получения этой информации из базы данных.

В целом, всякий раз, когда страница загружается на вашем сайте, она создается «на лету». Код PHP используется для того, чтобы получить доступ к базе данных MySQL и получить всю информацию, которая требуется для создания страницы. Одни PHP-запросы получают заголовок записи, другие – захватывают имя автора, третьи – берут дату публикации и т.д.

Вернемся к нашему сообщению об ошибке: «Error establishing a database connection». Оно означает, что по каким-то причинам PHP-код не смог соединиться с базой данной MySQL, чтобы получить информацию, которая требовалась для создания страницы.

Именно по этой причине на экране с ошибкой красуется лишь одно сообщение. Если вы не можете подключиться к базе данных, вы не знаете, что выводить на экран; нет никакой доступной информации о вашем сайте.

Что приводит к этой ошибке?

В то время как само сообщение об ошибке является достаточно ясным, причины, отвечающие за его появление, зачастую не совсем понятны.

Есть много разных причин, почему ваш сайт может иметь проблемы с подключением к вашей базе данных, однако их обычно можно разбить по трем категориям:

  1. Ваши учетные данные для входа в БД являются неверными. Ваша база данных использует отдельный логин и пароль. Если эти данные были недавно изменены, ваш сайт не сможет подключиться к БД, используя старые учетные данные.
  2. Ваша база данных была повреждена. Привести к такому печальному исходу могут самые разные причины, начиная с установки некачественного плагина и заканчивая ударом молнии в сервер (правда, это не самый распространенный вариант).
  3. Сервер, на котором расположена ваша БД, в данный момент не работает. Сервер с вашей базой данных может выйти из строя из-за каких-либо проблем или ошибок на стороне хостинг-компании. Также он может «лежать» из-за того, что на ваш сайт обрушился большой поток трафика, который сервер просто не смог обработать.

Таким образом, учитывая все возможные ситуации, как мы можем справиться с возникшей проблемой?

Решение проблем с «Error Establishing a Database Connection»

1. Определяем, с чем произошла ошибка.

Появляется ли эта ошибка только при обращении к wp-admin или же ваш сайт полностью лежит? А может, у вас другая ситуация: ваш сайт не работает, но при попытке входа вы видите несколько иную ошибку: «One or more database tables are unavailable. The database may need to be repaired»?

Все это говорит о том, что ваша база данных была повреждена.

WordPress обладает встроенным методом восстановления базы данных, однако для начала вам нужно будет включить эту возможность. Чтобы сделать это, вы должны иметь доступ к wp-config.php, который содержит ваши параметры и конфигурацию сборки WordPress.

Вы можете найти wp-config в корневой папке вашей сборки WordPress. Получить к ней доступ можно через cPanel: выберите File Manager и перейдите к папке, в которой у вас установлен WordPress.

Как только вы откроете wp-config, добавьте к нему следующую строку в самый конец файла:

define( 'WP_ALLOW_REPAIR', true );

Эта строка позволит вам оптимизировать и восстановить вашу базу данных. Перейдите по ссылке: www.yourwebsite.com/wp-admin/maint/repair.php (вместо yourwebsite.com введите реальный URL-адрес).

wordpress-database-repair

Вы должны увидеть страницу, показанную выше, с двумя возможностями восстановления – «repair» и «repair and optimize». Учтите, что оптимизация займет дополнительное время.

Обратите внимание, что страница восстановления базы данных никак не защищена; любой может получить доступ к этой странице по одному лишь URL. Как только вы восстановите вашу базу данных, обязательно удалите строку, добавленную ранее, из файла wp-config. В итоге вы ограничите доступ к этой странице.

Если ошибка пропала, вы можете закрыть wp-config и вернуться к нормальной работе с сайтом.

Если все это вам не помогло, давайте перейдем ко второму этапу восстановления сайта.

2. Проверяем учетные данные БД в wp-config

Если первый шаг не помог вам, то в таком случае вам нужно проверить, корректно ли заданы параметры базы данных в файле wp-config.

Удивлены, каким образом ваши учетные данные, работавшие ранее, перестали это делать? Смена хостинг-компании, изменение имени БД или пользовательской информации может привести к тому, что ваш wp-config файл будет содержать старые данные.

У вас может быть по-прежнему открыт файл wp-config, оставшийся еще с прошлого шага. В противном случайте войдите в cPanel хостинга и откройте File Manager. Перейдите к папке, в которую вы устанавливали WordPress, и найдите в ней файл, названный wp-config.php. Откройте его для редактирования.

Вы увидите учетные данные для вашей базы данных – обычно они расположены в самом верху файла. Выглядят они обычно следующим образом:

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

Как вы можете видеть, здесь есть несколько информационных разделов, которые требуются WordPress для доступа к вашей БД:

  1. Название БД (DB_NAME)
  2. Логин для входа (DB_USER)
  3. Пароль для входа (DB_PASSWORD)
  4. Хост базы данных (DB_HOST)

Если какое-либо из этих значений будет некорректным, WordPress не сможет подключиться к базе данных.

Проверить базу данных вне WordPress можно при помощи PHPMyAdmin – инструмента, который используется для редактирования базы данных MySQL. PHPMyAdmin включен во многие тарифные планы хостингов, и вы можете найти его в консоли cPanel.

Предупреждение: Будьте аккуратны при работе с PHPMyAdmin, поскольку этот инструмент ведет прямую работу с базой данных.

Как только вы войдете в PHPMyAdmin, вы увидите список баз данных на вашем сервере. Щелкните по той из них, которая будет соответствовать названию БД в файле wp-config (значение DB_NAME).

Не видите ни одной базы данных? В таком случае обратитесь к вашему хостингу, поскольку, скорее всего, проблема связана с вашим сервером.

После щелчка по названию базы данных вы увидите основной экран, содержащий названия таблиц вашей БД. Чтобы убедиться в том, что это – корректная БД, вы можете найти таблицу под названием wp_options и щелкнуть по опции Browse рядом с ней. Вы должны увидеть название вашего сайта, URL, а также все основные настройки. Теперь вы знаете, ту ли базу данных вы открыли. Если нет, то настройте ее должным образом в wp-config.

Давайте теперь проверим логин и пароль.

Есть несколько способов проверить их. Я предложу вам два варианта.

  1. Вы можете создать простой .php файл для тестирования того, сможете ли вы подключиться к вашей базе данных с учетными данными из файла wp-config
  2. Вы можете создать нового пользователя с паролем, и обновить файл wp-config, внеся в него новую информацию. Делать это надо в том случае, если первый способ не сработал.

Вариант 1. Тестируем существующие учетные данные.

Создаем файл в каталоге WordPress – пусть он называется testconnection.php (название не важно, главное чтобы он имел расширение .php). Вставляем в него следующий код:

<?php
$testConnection = mysql_connect('localhost', 'root', 'password');
if (!$testConnection) {
die('Error: ' . mysql_error());
}
echo 'Database connection working!';
mysql_close($testConnection);
?>

Как только вы создадите этот файл, просто перейдите по соответствующему URL в браузере (к примеру, site.com/testconnection.php). Вы увидите либо сообщение об удачном соединении, либо ошибку с детальной информацией.

Если логин и пароль не работают, мы можем создать нового пользователя.

Вариант 2. Создаем нового пользователя для БД (новый логин и пароль).

Сделать это мы можем с помощью другого инструмента в cPanel, который называется MySQL® Databases. Переходим к нему, затем прокручиваем вниз до заголовка: MySQL Users: Add New User. Задаем имя пользователя, а также сложный пароль. Щелкаем — Create User. Теперь прокручиваем до заголовка Add User To Database, и выбираем ваше новое имя пользователя и вашу базу данных WordPress, после чего щелкаем по Add. Обновляем файл wp-config, введя в него ваше новое имя пользователя и пароль.

Теперь название вашей БД, имя пользователя и пароль являются корректными. Остался только DB_HOST.

В большинстве случаем значение DB_HOST должно быть localhost, однако это зависит от настроек вашего хостинга. В WordPress есть список значений DB_HOST для популярных хостингов. Если ваш хостинг не перечислен там, то в таком случае обратитесь к нему за уточнениями.

3.Все еще появляется ошибка?

Если вы выполнили все шаги, приведенные выше, и ваш сайт все равно не работает, то в таком случае проблема заключается в вашем хостинге. Обратитесь в службу поддержки вашего хостинга и предоставьте им всю информацию по возникшей ошибке, а также те действия, которые вы совершили, пытаясь эту ошибку исправить – все это позволит компании быстрее справиться с проблемой.

Источник: www.elegantthemes.com/blog

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.

Окт 22, 2020

Elena B.

7хв. читання

Как исправить Ошибку Error Establishing a Database Connection в WordPress

В этом руководстве мы будет обсуждать различные методы устранения ошибки Error establishing a database connection в WordPress.

Проще говоря, это сообщение об ошибке указывает на то, что вашему сайту не удалось получить информацию из базы данных, необходимую для отображения страницы.

WordPress использует PHP в качестве основного языка и систему управления базами данных MySQL. Каждый раз, когда кто-то посещает ваш сайт, определённые команды PHP извлекают информацию о вашем сайте из базы данных и показывают её пользователю. Если этого не произойдёт, ваш сайт не сможет загрузиться, и появится сообщение об ошибке WordPress.

База данных — это программное обеспечение, используемое для удобной организации, хранения и извлечения данных в другое программное обеспечение. Поскольку WordPress является CMS, он использует базу данных для хранения всего содержимого вашего WordPress сайта. Таким образом, когда пользователь выполняет любые действия на вашем сайте, он отправляет запрос к базе данных.

Как результат ошибки Error establishing a database connection в WordPress, ваш сайт становится недоступным и теряет трафик.

Продолжайте читать это руководство, чтобы узнать все причины появления этой ошибки и пути её устранения.

Как устранить “Error Establishing a Database Connection” в WordPress?

Вот пять наиболее распространённых решений, с помощью которых можно исправить ошибку WordPress Error establishing a database connection. Но прежде чем вы попробуете, рекомендуем загрузить резервную копию данных вашего сайта. Вы можете найти больше информации о том, как это сделать, здесь.

Методы быстрого исправления ошибки

  1. Проверка данных для подключения к базе данных
  2. Восстановление базы данных WordPress
  3. Исправление повреждённые файлов
  4. Проверка сервера вашей базы данных
  5. Создание новой базы данных

Метод 1. Проверка данных для подключения к базе данных в wp-config.php

Одна из наиболее распространённых причин возникновения ошибок при попытке установить соедниение с базой данных, связана с неправильными учётными данными для входа. Это обычно происходит после того, как владелец веб-сайта переходит к другому хостинг-провайдеру. Если и интерфейс, и серверная часть вашего сайта выдают ошибку, этот метод должен решить проблему.

В первую очередь вам нужно проверить, совпадает ли информация для входа в базу данных с той, что ваш сайт хранит в файле wp-config.php.

Чтобы получить доступ к файлу wp-config, используйте FTP-клиент, например FileZilla, или файловый менеджер WordPress в панели управления хостингом.

Если вы решили использовать файловый менеджер, перейдите в папку /public_html/, щёлкните правой кнопкой мыши по файлу wp-config.php и выберите «Редактировать».

Файловый Менеджер в hPanel

Затем найдите следующие данные:

  • DB_NAME – имя базы данных
  • DB_USER – имя пользователя
  • DB_PASSWORD – пароль
  • DB_HOST – сервер базы данных

Информация в Файле wp-config.php

После этого перейдите в Базы данных MySQL и найдите своё текущее имя базы данных в разделе Список текущих баз данных и пользователей MySQL. Там вы увидите следующую информацию: имя базы данных, пользователя БД и хост.

Список Баз Данных в hPanel

Если данные для входа в вашем файле wp-config.php отличаются от тех, что вы нашли в разделе базы данных MySQL, измените информацию в файле wp-config.php.

Отредактируйте эти строки:

define('DB_NAME', 'в_этой_строке_введите_текущее_имя_вашей_базы_данных'); 
define('DB_USER', 'в_этой_строке_введите_ваше_текущее_имя_пользователя'); 
define('DB_HOST', 'в_этой_строке_введите_ваш_текущий_localhost');

Завершив редактирование файла, обновите ваш WordPress сайт, чтобы узнать, исчезла ли ошибка Error establishing a database connection.

Если ошибка не исчезла, возможно, значение DB_PASSWORD по-прежнему остаётся неправельным. Чтобы решить эту проблему, вам необходимо сбросить пароль MySQL.

Для этого просто вернитесь в меню Базы данных MySQL, щёлкните по своей текущей базе данных и выберите Изменить пароль. После ввода нового пароля нажмите кнопку Обновить.

Если имя вашей базы данных, имя пользователя и хост указаны правильно, стоит проверить информацию о хосте базы данных. Как правило, с WordPress в качестве хоста базы данных компании веб-хостинга используют localhost. В то время как компании управляемого WordPress хостинга могут использовать отдельные серверы.

В таком случае вам нужно будет связаться с вашей хостинговой компанией, чтобы узнать информацию о хосте вашей базы данных.

Обратите внимание, если вы недавно изменили хостинг-провайдера, обязательно дважды проверьте данные DB_HOST. В большинстве случаев localhost не меняется, но некоторые веб-хосты используют IP-адрес или другой URL.

Метод 2. Восстановление базы данных WordPress

Ваша база данных может быть повреждена, если на панели администратора WordPress отображается сообщение об ошибке вроде One or more database tables are unavailable. The database may need to be repaired (Одна или несколько таблиц недоступны. База данных должна быть восстановлена). Эта ошибка появится только на сервере, тогда как на сайте вы увидите сообщение error establishing a database connection.

К счастью, вы можете легко восстановить базу данных, вставив следующую функцию в файл wp-config.php:

define('WP_ALLOW_REPAIR', true);

Обязательно убедитесь, что вставили функцию перед разделом “That’s all, stop editing! Happy blogging.”

Вставка соответствующей функции в файл wp-config-php, чтобы исправить ошибку error establishing a database connection message

Сохранив изменения, перейдите на http://www.vashsite.com/wp-admin/maint/repair.php. Здесь у вас будет два варианта восстановления вашей базы данных.

Выберите необходимую вам опцию – Починить базу данных или Починить и оптимизировать базу данных.

После восстановления базы данных не забудьте вернуться к файлу wp-config.php и удалить функцию. Это очень важно, поскольку, если вы этого не сдеалете, любой сможет получить доступ к URL-адресу страницы восстановления БД без входа в систему.

Метод 3: Исправление повреждённые файлов

Ещё одна возможная причина появления сообщения Error Establishing a Database Connection – повреждённая тема или плагин.

Если вы недавно установили новую тему, причина может именно в ней. Чтобы проверить это, перейдите в Внешний вид -> Темы и попробуйте активировать любой другой из доступных там шаблонов.

Ещё один способ – отключить все плагины, а затем активировать их по очереди, чтобы найти виновника.

Если вы не можете зайти в панель управления WordPress, отключите тему или плагины, переименовав соответствующие папки в файловом менеджере панели управления хостингом.

Войдите в файловый менеджер и откройте папку wp_content, которая находится в каталоге public_html. Затем переименуйте текущую используемую тему или папку plugins. Это отключит вашу тему или все ваши плагины сразу.

Переименование папки Plugins

Помните, что не следует отключать темы и плагины WordPress одновременно, чтобы выяснить причину проблемы.

Например, сначала переименуйте папку plugins, а затем обновите сайт. Если ошибка исчезнет и вы сможете получить доступ к панели управления WordPress, значит, вы точно знаете, что проблема в одном из плагинов.

Но как узнать, какой именно плагин WordPress вызывает проблему?

Что ж, отключив их все, восстановите исходное имя папки plugins. Плагины WordPress по-прежнему будут неактивны, но теперь вы сможете изменять настройки в админке.

Список плагинов в консоли WordPress

После этого активируйте плагины WordPress один за другим, каждый раз перезагружая свой сайт. Продолжайте делать это до тех пор, пока не найдёте тот, который вызывает ошибку error establishing a database connection.

Совет: Не забудьте удалить тему или плагин, которые вызывают ошибку.

Если это не сработает, вы также можете попробовать повторно загрузить основные файлы WordPress. Для этого скачайте свежую версию WordPress и распакуйте архив на свой компьютер. Внутри папки удалите файл config.php и папку wp-content. После их удаления откройте FTP-клиент и загрузите оставшиеся файлы в папку root WordPress.

Таким образом, вы безопасно перезапишите все эти файлы на вашем реальном сервере.

Метод 4: Проверка сервера вашей базы данных

Если вы попробовали описанные выше методы, но WordPress по-прежнему не может установить соединение с базой данных, возможно, ваш сервер MySQL не работает.

Это может произойти по многим причинам, но одна из них связана с интенсивным трафиком на сервере. Это когда ваш хост-сервер не может обработать количество пользователей, пытающихся получить к нему доступ, что приводит к ошибке соединения.

Если причина в трафике, ваш сайт станет медленным и может выдать сообщение error establishing a database connection. Это обычно происходит, когда на серверах хостинг-провайдера есть ограничения. В таком случае обратитесь к своему провайдеру веб-хостинга и попросите его проверить, отвечает ли ваш сервер MySQL.

Если у вас более одного сайта, которые используют один и тот же сервер, проверьте работает ли ваш SQL-сервер и на них.

Пользователям, у которых только один сайт, рекомендуется перейти в панель управления хостингом, войти в phpMyAdmin и подключиться к базе данных.

Меню phpMyAdmin в hPanel

Если вам удастся установить соединение, проверьте, есть ли у вашего пользователя БД WordPress необходимые права.

Создайте новый файл с именем testconnection.php (или любым другим, которое вы можете запомнить с расширением .php) и вставьте в него этот код:

<?php 
$link = mysqli_connect('localhost', 'пользователь', 'пароль'); 
if (!$link) { 
die('Could not connect: ' . mysqli_error()); 
} 
echo 'Connected successfully'; 
mysqli_close($link); 
?>

Обязательно замените имя пользователя и пароль своей информацией. Затем загрузите этот файл на сайт и попробуйте зайти на него в браузере.

Если соединение с базой данных будет успешно установленно, это означает, что у вашего пользователя достаточно прав, и что причина ошибки error establishing a database connection в чём-то другом.

Если ваш веб-сайт размещён на общем сервере, а трафик продолжает расти, нагрузка на сервер будет тоже увеличиваться, что может вызвать проблему соединения с базой данных. Плагины кеширования, такие как W3 Total Cache, WP Rocket или WP Super Cache – хорошие инструменты, которые помогут предотвратить дальнейшие проблемы.

Метод 5: Создание новой базы данных

Если ни один из вышеперечисленных методов не помог, значит ваша база данных может быть полностью повреждена и не подлежит восстановлению.

В таком случае вам необходимо создать новую базу данных MySQL и пользователя. Для этого перейдите на страницу Базы данных MySQL и заполните форму вверху.

Форма создания базы данных MySQL в hPanel

Создав новую базу данных MySQL, импортируйте (англ.) резервную копию БД, чтобы не делать всё с нуля.

Дополнительные методы 

Если ни один из перечисленных выше методов не помог, вот ещё несколько бонусных советов, которые сработали для других пользователей.

  1. Обновите WordPress. Перейдите в свою панель управления, затем в phpMyAdmin > База данных WordPress. Щелкните по SQL в верхнем меню и вставьте следующий код:
    UPDATE wp_options SET option_value='YOUR_SITE_URL' WHERE option_name='siteurl'
  2. Попросите помочь вам. Нет ничего плохого в том, чтобы попросить о помощи. Обратитесь в свою хостинговую компанию или в службу поддержки клиентов. Они, наверняка, помогут устранить проблему с подключением, приняв необходимые меры за вас или показав, как это сделать.
  3. Перезагрузите сервер. Пользователи выделенных серверов, локальных серверов и VPS (виртуальных частных серверов) также могут попытаться перезагрузить свои серверы. При перезапуске веб-сервера и сервера базы данных некоторые ошибки могут просто исчезнуть.
  4. Восстановите последнюю резервную копию. Это следует делать только в том случае, если вы не боитесь потерять данные, которые были добавлены после последнего резервного копирования. Проверьте, есть ли у вашего хостинга функция автоматического создания бэкапов, чтобы узнать, когда была создана последняя резервная копия. Возможно, вам придётся восстановить как вашу базу данных, так и ваши файлы.

Возможные причины ошибки

Есть несколько причин, по которым на сайте WordPress может появится сообщение «Error Establishing a Database Connection»:

  • Неверные данные для подключения к базе данных. Если были внесены какие-либо изминения в учётные данные для подключения к БД, изменилось имя пользователя или пароль, старые данные, хранящиеся в ваших файлах WordPress, будут недействительными.
  • Повреждённая база данных. Может быть результатом попытки взлома, сбоя в работе плагина или установки несовместимой темы.
  • Всплеск трафика. Внезапный рост спроса может привести к тому, что ваша база данных перестанет отвечать из-за слишком большой нагрузки на сервер.
  • Нерабочий сервер базы данных. Иногда сервер, на котором хранятся файлы вашего сайта, может не работать по какой-либо причине.

Прежде чем предпринимать какие-либо действия по устранению ошибки, проверьте, отображается ли сообщение error establishing a database connection и в панели администратора WordPress.

Вот как может выглядеть ваша админка WordPress:

Сообщение error establishing a database connection в админке WordPress

Если вы видите такое сообщение, значит проблема в неверных учётных данных для входа. Однако, если появляется другое сообщение об ошибке, причиной может быть повреждённая база данных или всплеск трафика.

Заключение

Сообщение об ошибке “Error Establishing a Database Connection” на вашем сайте WordPress может изрядно подпортить настроение. Сайт не загружается, а значит есть риск потерять трафик и клиентов.

Ошибка возникает, когда вашему сайту не удаётся получить информацию из базы данных. Это может быть вызвано рядом причин, таких как неправильные учётные данные для входа в файле wp-config.php, конфликты темы или плагина WordPress, всплеск трафика.

Эти три метода должны помочь устранить проблему:

  • Исправление неправильных учётных данных. Убедитесь, что учётные данные в вашем файле wp-config.php совпадают с данными в базе данных MySQL.
  • Ремонт базы данных. Если ваша база данных повреждена, восстановите её, вставив функцию define(‘WP_ALLOW_REPAIR’, true); в файл wp-config.php.
  • Исправление повреждённых файлов. Деактивируйте тему или плагин через панель управления WordPress или переименуйте папки с панели управления хостингом.
  • Создание новой БД. Создайте новую базу данных MySQL и импортируйте резервную копию.

Оказывается, ошибка подключения к базе данных в WordPress не так и страшна. Просто следуйте инструкциям, и ваш сайт заработает в кратчайшие сроки!

Author

Елена имеет профессиональное техническое образование в области информационных технологий и опыт программирования на разных языках под разные платформы и системы. Более 10 лет посвятила сфере веб, работая с разными CMS, такими как: Drupal, Joomla, Magento и конечно же наиболее популярной в наши дни системой управления контентом – WordPress. Её статьи всегда технически выверены и точны, будь то обзор для WordPress или инструкции по настройке вашего VPS сервера.

The “Error establishing a database connection” message strikes fear in a WordPress users heart, prompting many a panicked support request. You try to load a page, but all you see is a white box with a mysterious error message. WordPress is down and the “helpful” suggestions beneath the error are more confusing than useful.

How can you fix a database error when you can’t even open the admin dashboard to see what’s wrong?

Fortunately, “Error Establishing a Database Connection” is straightforward to put right if you know what’s going on. Let’s take a look at WordPress’s relationship with its database, which is called MySQL®, what can go wrong, and, most importantly, what you can do to put WordPress and MySQL back on speaking terms.

Why Does WordPress Need a Database?

A WordPress site is composed of two parts: the files and the database.

When you download WordPress, there are static files and code files written in PHP, but you won’t find pages and posts, usernames and passwords, comments, or configuration data — that’s all stored in a MySQL database.

MySQL is a database server: it manages databases, tables, and the data stored in them. WordPress communicates with MySQL over the network, authenticating with a username and password before sending an SQL query that tells the database what to do.

For example, loading the WordPress home page executes a PHP file — usually the home.php or index.php file, depending on how the site is configured. The code connects to the database and retrieves the home page’s content, slotting it into a template that generates an HTML document.

A connection error is WordPress’s way of telling you that it can’t get the information it needs to build the page you’re trying to load. WordPress asked for data, and the database ignored it or said no. To fix the error, we have to figure out why MySQL is misbehaving.

There are several possible causes:

  • Network connection errors — The database can’t be reached on the network. This might be because the database server is overloaded or the hosting provider has a network issue.
  • Incorrect database credentials — WordPress is attempting to authenticate with credentials the database doesn’t recognize, so the request is denied.
  • WordPress’s files are corrupted — Corrupt files can lead to invalid database requests or requests with the wrong credentials — a problem often caused by malware or a hacked WordPress installation.
  • The database is corrupted — Corrupt databases are less likely than corrupt files, but editing the database manually and poorly coded plugins can cause database corruption. However, a corrupted database will usually show an error message such as “One or more databases are unavailable” instead of “Error Establishing a Database Connection.”

In summary, WordPress database errors usually mean WordPress can’t connect to or authenticate with the database or the database can’t respond with the right information.

How Do I Fix Database Connection Errors in WordPress?

It can be challenging to identify the error’s cause, so the best approach is to try the most likely fixes until your WordPress site starts working again.

Verify Database Credentials in cPanel

WordPress uses four pieces of information to talk to MySQL: 

  • The database name 
  • The database server’s hostname 
  • A username 
  • A password 

They are stored as variables in the wp-config.php file in the WordPress installation’s root directory, and they look like this:

/** MySQL database username */ 
define(‘DB_USER’, ‘xxxxxx’);

The first step in verifying your database credentials is comparing the values listed in the wp-config.php file to those listed in the database. Open phpMyAdmin in cPanel and find the WordPress database in the left menu. Make sure the database name and the DB_NAME variable in wp-config.php match. Also, verify that the hostname matches the name in the database server section: it will almost certainly be “localhost.”

Next, check the “Users” section within the database entry to ensure that database’s username and password match the values WordPress is using. You can edit the values in the database to make them match those in wp-config.php or edit values in  wp-config.php directly using the cPanel File Manager’s HTML Editor.

If the database credentials check out but the error persists, it’s time to consider file or database corruption.

Repair the Database

Corrupt files are more likely, but minor database corruption is easier and less risky to fix so it’s worth trying first. There are a couple of ways to go about WordPress database repair. The first is to select phpMyAdmin in cPanel, navigate to your database, select all the tables, and click on the “repair table” item in the dropdown menu.

The second method takes advantage of WordPress’s built-in database repair mode, which you can activate by adding the following line to the wp-config.php file:

define(‘WP_ALLOW_REPAIR’, true);

Next, navigate to this URL:

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

Choose the repair option and wait while WordPress does its thing. It might take a while but should handle most common database corruption issues. Be sure to remove the line of code you added to wp-config.php when you have finished. Anyone can access the database repair URL and you don’t want it triggered by malicious visitors.

Replace Corrupt WordPress Files

WordPress’s files can be corrupted by hardware problems, malware, or user errors. The goal here is to replace corrupt files with new ones freshly downloaded from WordPress.org while leaving your site’s plugins and themes in place.

Download a copy of WordPress, unzip it, and navigate to the “wordpress” directory. Delete the wp-content folder and the wp-config.php and wp-config-sample.php files.

Open the affected WordPress site’s root folder in cPanel File Manager and upload all the remaining files and folders from your local copy of WordPress. If cPanel asks whether to overwrite existing files, say yes.

All of WordPress’s core files will be replaced with pristine new files. If this doesn’t resolve the database error, you may want to try replacing wp-config.php too, in which case you will have to edit the new version to add the correct database credentials, as discussed above.

If none of these methods resolves the error, it is time to restore the WordPress site—both the files and the database—from a recent backup that was made before the connection error occurred.

It can be frightening when you first see “Error Establishing a Database Connection” on your WordPress site, but hopefully you now understand what the error means and the steps you can take to restore harmony between WordPress and its database. 

If you have any further questions about fixing WordPress database errors with cPanel or wish to discuss anything cPanel related, please join us on our official Discord channel, our official cPanel subreddit, or our Support Forum.

Понравилась статья? Поделить с друзьями:
  • Error establishing a database connection ubuntu wordpress
  • Error establishing a database connection open server
  • Error establishing a database connection localhost
  • Error establishing a database connection error establishing a database connection
  • Error establishing a database connection beget