Error establishing a database connection ubuntu wordpress

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

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

Эта ошибка будет выводиться на каждой странице вашего сайта и вы потеряете посетителей, а также доход, который могли получить. В этой статье мы рассмотрим почему возникает ошибка error establishing a database connection wordpress, а также способы борьбы с ней на хостинге и на VPS.

Почему возникает ошибка error establishing a database connection wordpress

Ошибка установки соединения с базой данных wordpress или error establishing a database connection wordpress по-английски может возникать по многим причинам. Давайте сначала рассмотрим почему она может появляться на хостинге. Я раньше размещал свой сайт на хостинге и встречался с ней довольно часто. Тут может три причины:

  • База данных не создана. То есть, возможно, раньше она и была, но потом ее кто-то удалил и ее больше нет. Если база данных есть, но она пуста, то wordpress покажет сообщение что он неверно установлен и его нужно переустановить;
  • Данные доступа к базе данных в файле wp-config.php указаны неверно. Если хост, пользователь базы или его пароль неверны, то вы не сможете к ней подключиться;
  • Достигнут лимит подключений. Обычно, хостинги не хотят чтобы клиенты перенагружали общую базу данных и устанавливают лимит на количество подключений от одного клиента, например, 8. Когда у вас будет большая посещаемость этого станет явно недостаточно и вы будете видеть такую ошибку время от времени, казалось бы, совсем без причины.

На VPS две первые причины все еще актуальны, но к ним добавляется еще несколько, поскольку это ваш сервер и за его работу отвечаете только вы:

  • Сервис баз данных не запущен — из-за некоторых ошибок во время работы сервис mariadb или mysql может завершить свою работу и, естественно, что тогда база будет недоступной.
  • Если база данных размещена на другом сервере, то, возможно, этот сервер недоступен из сети или был отключен.

Что делать с error establishing a database connection

Теперь попробуем разобрать каждый из вариантов и попытаться понять что делать с error establishing a database connection, а также для предотвращения ее появления в будущем.

1. Базы данных нет

Если базы данных больше не существует, вы ее случайно стерли или ее стер хостер, то у вас есть два пути — либо установить WordPress заново, либо восстановить базу данных mysql из резервной копии. Все настройки базы данных находятся в файле wp-config.php, который находится в корневом каталоге сайта. Скорее всего, на хостинге у вас не будет доступа по SSH и придется довольствоваться FTP.

Вы можете посмотреть как называется база данных в нем:

Затем убедитесь, с помощью Phpmyadmin, что она есть и в ней есть данные:

2. Неверные настройки

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

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

Проверить правильность ввода логина и пароля вы можете попытавшись войти с помощью них в Phpmyadmin:

Или используя консольную утилиту mysql если можете подключиться по ssh:

mysql -h хост -u пользователь -p имя_базы данных

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

3. Ограничения сервера

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

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

4. Сервис mysql не запущен

Эта проблема уже касается только VPS, поскольку на хостингах у вас нет доступа к таким службам и вы не сможете ничего сделать. На VPS вы можете делать все что угодно с любой службой. Чаще всего в качестве сервера баз данных используется MariaDB. Чтобы проверить запущена ли она в CentOS наберите:

systemctl status mariadb

В Ubuntu имя сервиса будет немного отличаться:

systemctl status mariadb-server

Если вы увидите надпись Iactive (dead) значит сервис не запущен. Почему? Это уже другой вопрос. Чтобы восстановить работоспособность сайта попробуйте запустить его:

systemctl start mariadb-server

Чаще всего сервер баз данных падает из-за нехватки памяти для работы движка innodb. Чтобы предотвратить такие падения в будущем можно сделать две вещи:

  • Удалить или остановить программы, потребляющие очень много памяти или увеличить количество памяти на сервере;
  • Настроить автоматический перезапуск MariaDB в случае, если она упала с помощью systemd. В этом случае вы даже не будете замечать, что были какие-либо проблемы и ошибка error establishing a database connection возникать не будет, но это только пока с памятью все не совсем уж плохо.

Чтобы заставить systemd следить за состоянием сервиса и перезапускать его по мере необходимости создайте файл /etc/systemd/system/mariadb.service.d/restart.conf и добавьте в него такое содержимое:

vi /etc/systemd/system/mariadb.service.d/restart.conf

[Service]
Restart=always

Затем обновите конфигурацию сервисов:

systemctl daemon-reload

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

systemctl show mariadb

Выводы

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

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

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

i have a blog with wordpress but sometimes i have problem with that

i got blow error

Error establishing a database connection
This either means that the username and password information in your wp-config.php file is incorrect or we can’t contact the database server at %s. This could mean your host’s database server is down.

Are you sure you have the correct username and password?
Are you sure that you have typed the correct hostname?
Are you sure that the database server is running?
If you’re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress Support Forums

and this is my config file

define('WP_HOME','http://www.mysite.com');
define('WP_SITEURL','http://www.mysite.come');
define('DB_NAME', 'mydbname');

/** MySQL database username */
define('DB_USER', 'dbusername');

/** MySQL database password */
define('DB_PASSWORD', 'dbpassword');

/** MySQL hostname */
define('DB_HOST', 'mysite.com');

why i got this error sometimes what do you think about this problem?

i contact with my admins server and they said «we dont have any problem with server and mysql service»

does my server have problem or my config have problem?

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.

Это – один из худших кошмаров для владельца веб-сайтов. Вы вводите 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

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!

The “error establishing a database connection” is probably one of the most common errors WordPress users can encounter. It’s closely tied to the white screen of death (WSOD). This error means your website is no longer communicating or has access to your WordPress database; thus, your entire website goes down.

You should resolve this error immediately, as this can directly affect your sales, traffic, and analytics.

But don’t worry, today we’ll discuss some common scenarios that cause this error and some easy ways to get your site back up and running in no time.

Check Out Our Video Guide to Fixing The “Error Establishing a Database Connection”

What Is The “Error Establishing a Database Connection”?

All the information on your WordPress site, such as post data, page data, meta information, plugin settings, login information, etc. is stored in your MySQL database. The only data not stored there is media content such as images and your theme/plugin/core files such as index.php, wp-login.php, etc.

When someone visits your website, PHP executes the code on the page, queries the information from the database, and then displays it to the visitor in their browser.

This error might just be tied with the White Screen of Death as one of the scariest errors you can encounter 💀 But this guide is here to help 💪Click to Tweet

If this isn’t working correctly, you are left with the “error establishing a database connection” message, as seen below. The entire page is blank because no data can be retrieved to render the page, as the connection is not working properly. Not only does this break the frontend of your site, but it will also prevent you from accessing your WordPress dashboard.

The Error establishing a database connection message in Chrome

“Error establishing a database connection” message in Chrome

However, visitors might not see this error on the frontend right away. That is because your site is most likely still serving from cache until it expires. For example, at Kinsta, all WordPress sites are cached for one hour by default. Therefore, if a site is still serving from the cache, it might appear acceptable to a visitor.

At Kinsta, our support team can increase the duration of your cache to, say, an hour or even a week if you want. If you have a site that doesn’t change very often, this can increase your site’s performance as it does not have to grab new files as often after the cache expires. And in cases like the above, the frontend of the site in most cases (unless you have a script or part of your site breaking the cache) would stay up a lot longer.

When visitors try to access your site while this error is happening, it will generate a 500 HTTP status code in your logs. This same status code appears with an “internal server error.” It means that something went wrong on the server, and the requested resource was not delivered. When everything is working properly, your site will generate a 200 HTTP status code, which means everything is fine.

Error establishing a database connection 500 error in MyKinsta

“Error establishing a database connection” 500 error

If you’re a Kinsta client, you could also look at the 500 error breakdown report in MyKinsta analytics to see if it’s something that has been a reoccurring problem.

500 error breakdown

500 error breakdown

What Are the Most Common Causes of This Error?

So why exactly does this happen? Well, here are a few common reasons below. And don’t worry, we will go into each of these more in-depth so you can know how to fix them. Typically you can resolve this error in under 15 minutes.

  • The most common issue is that your database login credentials are incorrect. Your WordPress site uses separate login information to connect to its MySQL database.
  • Your database is corrupted. With so many moving parts with themes, plugins, and users constantly deleting and installing them, sometimes databases get corrupted. This can be due to a missing or individually corrupted table, or perhaps some information was deleted by accident.
  • You may have corrupt files in your WordPress installation. This can even happen sometimes due to hackers.
  • Issues with your database server. Several things could be wrong on the web host’s end, such as overloading the database from a traffic spike or being unresponsive from too many concurrent connections. This is common with shared hosts as they utilize the same resources for many users on the same servers.
  • A spike in traffic. Depending on the web host you use, your server might be unable to handle many concurrent database connections. An increase in traffic can lead to temporary problems with the database.

How To Fix The “Error Establishing a Database Connection”?

Before troubleshooting the error, we recommend taking a WordPress site backup. Many of the recommendations below involve manipulating information in your database, so you don’t want to make things worse. You should always backup before trying to fix things on your WordPress site, no matter how tech-savvy you think you are.

You can use a popular WordPress backup plugin such as VaultPress or WP Time Capsule to backup your files and database.

If you are a Kinsta user, you can take advantage of our one-click backup feature. Click into your WordPress site in MyKinsta, click on “Backups” and then on “Back up now.”

Backup WordPress site in MyKinsta dashboard

Backup WordPress site

You then also have the option to restore a backup to production or staging. Or you can manually backup your MySQL database using phpMyAdmin. Once you have a successful backup, it is time to troubleshoot your database connection issues.

1. Check Your Database Login Credentials

The first thing to do is check to ensure your database login credentials are correct. This is by far the most common reason why the “error establishing a database connection” message occurs. Especially right after people migrate to a new hosting provider. The connection details for your WordPress site are stored in the wp-config.php file, which is generally located at the root of your WordPress site.

It contains four important pieces of information that must be correct for the connection to occur successfully.

Database Name

// ** MySQL settings ** //

/** The name of the database for WordPress */

define('DB_NAME', 'xxxxxx');

MySQL database username

/** MySQL database username */

define('DB_USER', 'xxxxxx');

MySQL database password

/** MySQL database password */

define('DB_PASSWORD', 'xxxxxxxxx');

MySQL hostname (server)

/** MySQL hostname */

define('DB_HOST', 'localhost');

To access your wp-config.php file, you can connect to your site via SFTP and browse to the root of your site. Or, if you are using cPanel, you can click on “File Manager,” browse to the root of your site, and right-click to edit the file.

cPanel file manager

Here is an example below of what the file looks like when opened.

wp-config.php credentials

wp-config.php credentials

You need to now check your current values against those on your server to ensure they are correct. Follow the directions below for cPanel and Kinsta users.

Check Database Credentials in cPanel

The first thing to check is the database name. To do this, you must log in to phpMyAdmin in cPanel under the Databases section.

Screenshot showing cPanel phpMyAdmin

cPanel phpMyAdmin

You should see your database name at the bottom on the left. You can ignore the “information_schema” database as this is something used by the host. You will then want to compare that name against the DB_NAME value in your wp-config.php file. If they match, then this isn’t the problem. If they don’t match, you need to update your wp-config.php file.

cPanel database name

cPanel database name

You can also verify this is the correct database by ensuring it contains your WordPress site’s URL. To do this, click on the database and then click into the wp_options table (this might be slightly different for security purposes, such as wpxx_options). At the top of the table, you will see values for your site’s URL and name. If these match your current site, you can rest assured you are in the right place.

Site URL check in phpMyAdmin

Check site URL in phpMyAdmin

If your database name was already correct and you still get the “error establishing a database connection” message, you will also want to check your username and password. To do this, you will need to create a new PHP file in the root directory of your WordPress site and input the following code. You can name it whatever you want, such as checkdb.php. Change the values of db_user and db_password with those in your wp-config.php file.

<?php

$test = mysqli_connect('localhost', 'db_user', 'db_password');

if (!$test) {

die('MySQL Error: ' . mysqli_error());

}

echo 'Database connection is working properly!';

mysqli_close($testConnection);

Then browse the file on your WordPress site: https://yourdomain.com/checkdb.php. If you get a “MySQL Error: Access denied,” then you know your username or password is wrong, and you will need to continue to the next step to reset your credentials.

Access denied for localhost

Access denied MySQL

Below is the message you want to see, “Database connection is working properly.” But of course, if it were, then you wouldn’t be here. Be sure to delete/remove this file after you are done testing.

Database connection working properly

Database connection working properly

So next, you need to reset your username and password. In cPanel, click on MySQL Databases under the Databases section.

MySQL databases in cPanel

cPanel MySQL databases

Scroll down and create a new MySQL user. Try and pick a unique username and password so they can’t easily be guessed. The password generator tool they provide works excellent. Then click on “Create User.” Alternatively, you could change the password on this screen for the current database user.

Creating a new MySQL user in cPanel

Create a new MySQL user

Then scroll down and add your new user to your database. The next screen will ask which privileges you want to assign. Select “All Privileges.”

Add user to database in cPanel

Add user to the database in cPanel

Then take those new credentials and update your wp-config.php file. You will want to update the DB_USER and DB_PASSWORD values. You could also rerun the test file from earlier. This should then resolve your credentials issue. If not, you could still have the wrong hostname (DB_HOST). Some hosts use different values.

See a list of some common DB host values. Typically this will be localhost. But you can always reach out to your hosting provider or check their documentation if you aren’t sure. Some might also use 127.0.0.1 instead of localhost.

If you have followed everything above and are still receiving the “error establishing a database connection” message, proceed to the following troubleshooting steps below.

Check Database Credentials With Kinsta

If you are a Kinsta user, checking your credentials against your wp-config.php file and the server is much easier! All you need to do is click on the info section of your site, and towards the bottom, you will see the database name, username, and password. By default, Kinsta uses localhost for the DB_HOST.

Checking the database credentials in MyKinsta.

Checking your site’s database credentials in MyKinsta.

Then take those new credentials and update your wp-config.php file. You will want to update the DB_USER and DB_PASSWORD values. This should then resolve your credentials issue. If you need to reset these credentials, contact our support team. If you have followed everything above and are still receiving the “error establishing a database connection” message, proceed to the following troubleshooting steps below.

2. Repair Corrupt WordPress Database

In some cases, it could be that your database has become corrupt. This can occasionally happen (although not very often) as, over time, hundreds of tables are constantly added/removed by new plugins and themes. If you try to login to your WordPress site’s dashboard and are receiving the following error, it means your database is corrupt: “One or more database tables are unavailable. The database may need to be repaired.” It is important to note that you might only see this error on the back-end, whereas you see the “error establishing a database connection” message on the frontend.

WordPress has a database repair mode that you can initiate. Add the following to the bottom of your wp-config.php file.

define('WP_ALLOW_REPAIR', true);

Currently in WordPress repair mode

WordPress repair mode

Then browse to the following location on your WordPress site: https://yourdomain.com/wp-admin/maint/repair.php. You will then have the option to repair the database or repair and optimize the database. Since you are probably troubleshooting an outage on your site now, we recommend using the repair database option as it is quicker.

Repair and optimize database in WordPress

WordPress repair database

After running the repair of the database above, ensure that you remove the line of code you added to your wp-config.php file. Otherwise, anyone will be able to access the repair.php page. If you are running cPanel, you can also run a repair from within the MySQL databases screen.

Repair database option in cPanel

cPanel repair database

Or you could run a repair from within phpMyAdmin. Simply log in to phpMyAdmin, click on your database, and select all the tables. Then from the dropdown, click on “Repair table.” This is essentially just running the REPAIR TABLE command.

Repairing tables in phpMyAdmin

Repair tables in phpMyAdmin

And finally, your other option would be to run the repair using WP-CLI with the following command:

wp db repair

See more documentation on usage in the WordPress developer resources.

If you want to optimize your database, we have some great tutorials on how to optimize WordPress revisions for performance, along with how to convert your MyISAM tables to InnoDB. If you still have issues on your site, proceed to the next troubleshooting step.

Suggested reading: How to Fix the “MySQL Server Has Gone Away” Error in WordPress.

3. Fix Corrupt WordPress Files

The following possible reason you might see the “error establishing a database connection” message is that your WordPress core files have become corrupt. Whether this originated from an issue with transferring files via FTP, a hacker gaining access to your site, or a problem with your host, you can quickly fix this. However, we recommend taking a backup of your site before trying this.

You are going to replace the core version of WordPress on your site. You aren’t touching your plugins, themes, or media, just the WordPress installation itself.

However, you may lose any changes or custom code you’ve added to files such as .htaccess or wp-config.php. If you backed up your website before troubleshooting, you’d have copies of those files that you can restore later.

To get started, you must download a fresh WordPress copy from WordPress.org.

WordPress download page

Download WordPress

Unzip this file on your computer. Inside, you will want to delete the wp-content folder and the wp-config-sample.php file.

Unzip downloaded file to computer

Delete wp-content folder

Then upload the remaining files via SFTP to your site, overwriting your existing files. This will replace all the problematic files and ensure you have fresh ones that are clean and not corrupted. It is recommended to clear your browser cache after doing this. Then check your WordPress site to see if the error still exists.

4. Check for Issues With Your Database Server

If nothing above has helped resolve your issue, we highly recommend checking with your hosting provider as it could be an issue with your database server. For example, if there are too many concurrent connections to your database at once, it could generate an error. This is because many hosts limit their servers on how many connections are allowed at once. Utilizing a caching plugin can help minimize the database interactions on your site. If you are a Kinsta client, you don’t need caching plugins, as we have fast server-level caching.

This problem can happen a lot on shared hosts, as someone else could theoretically be affecting your site. This is because shared hosts utilize all the same resources on servers. This is another reason we recommend using a high-performance managed WordPress host, so things aren’t overcrowded. It also means the environment is typically fine-tuned to handle large amounts of traffic, specifically to WordPress sites.

The knowledgeable Kinsta support team is always a click away on the bottom right side of the dashboard and available 24/7 if you need help. And don’t forget we have representatives to assist you in multiple languages, including English, Spanish, French, Italian, and Portuguese.

Contact Kinsta support right from MyKinsta dashboard

Contact Kinsta support

5. Restore Latest Backup

And last but not least, you can always resort to a backup if needed. In some cases, this might be a faster way to resolve the issue if you aren’t worried about losing any data between when your last backup was taken. Many hosts have their own backup restore process. Remember that you might need to restore both your database and your files.

If you are a Kinsta user, you can quickly restore a backup of your site within the Backups section of your site. Choose the time you want to revert and click on “Restore to.” You can then select whether you want to restore to Staging or your Live site.

Restore WordPress backup in MyKinsta

Restore WordPress backup

You will then be prompted to confirm the restoration. Enter your site name and click on “OK.” It also creates a backup at the restoration time so you can undo the restoration if needed.

Confirm your backup restoration

Confirm WordPress restore

This error is not something to be taken lightly & can directly affect your sales, traffic, and analytics 😬 Learn how to fix it here ✅Click to Tweet

Summary

As you can see, there are quite a few ways to fix the “error establishing a database connection” in WordPress. The most common being invalid credentials in the wp-config.php file. Checking to ensure those are correct is the best place to start. The last thing you want for a website is to experience downtime.

Hopefully, one of the steps above helped you get your site back up and running. Remember, you can always restore your site from a backup if needed.

Have you experienced the “error establishing a database connection” message on your site? If so, were you able to resolve it? Let us know below in the comments.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

In this quick article, we’ll discuss how to troubleshoot and fix the Error establishing a database connection error on a WordPress site.

The Error establishing a database connection error is one of the most common errors which WordPress users can encounter while visiting your website. It’s pretty similar to the white screen of death (WSOD) error, which displays a blank page on your WordPress website, and you’re clueless about what to do next. In this case, though, it at least displays a helpful message, which allows you to debug further and fix it.

Having said that, this can be frustrating for you as a WordPress admin, if you don’t know the cause of this error, since your entire site goes down with this error. You’ll want to fix this error immediately, since it’s irritating for users to see this error with a blank page. And of course, you’ll lose all of your website traffic until you fix it.

Today, we’ll go through the possible solutions that could fix this error.

Primary Suspect: WordPress Database Details

In most cases, the reason for this error is the wrong database details in your WordPress configuration file. Since WordPress uses a database to manage your website content, it needs to connect to the database to run your site in the first place.

To connect to the database, WordPress needs the following information:

  • database host name
  • database username
  • database password
  • database name

WordPress stores all the above information in the wp-config.php configuration file, which is located in the document root of your website, so that’s the first thing you want to check. You can download the wp-config.php file by connecting to your site with an FTP client or you can use cPanel if it is supported by your host.

Try to find the following snippet in your wp-config.php file, which you’ve just downloaded.

1
/** The name of the database for WordPress */
2
define( 'DB_NAME', 'demo_db' );
3

4
/** MySQL database username */
5
define( 'DB_USER', 'demo_user' );
6

7
/** MySQL database password */
8
define( 'DB_PASSWORD', 'demopassword' );
9

10
/** MySQL hostname */
11
define( 'DB_HOST', 'localhost' );

As you can see, it holds all the details that WordPress needs to connect to the database. If any of these are wrong, WordPress won’t be able to connect to the database, and you’ll end up with the Error establishing a database connection error.

Make sure that all the details are correct, and if you’re in doubt, you can always ask your hosting provider to verify them. If any of these are wrong, correct them and upload the wp-config.php file on your server. In most cases, that should fix it and you should notice that your website is working again!

On the other hand, if you’re sure that all these details are correct in your wp-config.php file, and you’re still getting this error, move on to the next step.

Connection to Your Database Server

If you’ve already checked that the database settings in your wp-config.php file are correct, and your site is still down with the Error establishing a database connection error, the next thing you should check is the status of your database server.

If your database server is down for any reason, WordPress won’t be able to connect to the database and will produce this error. The most common reason for your database server being down is heavy traffic on your website, which can’t be handled with the limited resources on your server.

If you’re on a dedicated server and have shell access to your server, you can try rebooting your database server to see if that helps to fix this error. On many occasions, this turns out to be one of the most effective solutions.

Finally, if you haven’t got shell access or you are not comfortable with running commands in the shell, you can contact your hosting provider and confirm the availability of your database server. If there’s something unusual with your database server, they should probably fix it and get back to you, and that should also solve this error for you.

Corrupted Database

In very rare cases, a corrupted database may also produce this error. There are various reasons for your database to get corrupted so that WordPress will not be able to use it.

In this case, the best option is to restore your recent database backup and check if it does the trick. Unfortunately, if you don’t have any database backups, you can’t perform this step. So it’s always a good habit to make database backups regularly.

There are a few different ways that you could restore your database. If you’ve got shell access to your server, you could use a command to restore your database from the database dump file. On the other hand, you can use a tool like phpMyAdmin, if you’re using the MySQL database. Finally, you can always contact your hosting provider or a developer if you don’t know how to restore it.

Needless to say, it’s a good idea to back up your WordPress site and database regularly. If you want to learn more about backing up your WordPress website, check out some of our other tutorials here on Envato Tuts+.

Conclusion

In this quick article, we discussed a couple of possible solutions to the Error establishing a database connection error in WordPress. We looked at how to diagnose an error in your WordPress database configuration, how to make sure WordPress can connect to your database, and what to do in case of a corrupted database.

Did you find this post useful?

Sajal Soni

Software Engineer, FSPL, India

I’m a software engineer by profession, and I’ve done my engineering in computer science. It’s been around 14 years I’ve been working in the field of website development and open-source technologies.

Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I’ve worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I’ve also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce.

I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!

Окт 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 сервера.

Понравилась статья? Поделить с друзьями:
  • Error establishing a database connection localhost
  • Error establishing a database connection error establishing a database connection
  • Error establishing a database connection beget
  • Error establishing a database connection apache
  • Error enospc no space left on device write