How to Fix “Error Establishing A Database Connection” in WordPress
“Error Establishing a Database Connection” is a common issue that occurs on WordPress. This error happens when the site refuses to connect to the WordPress database.
If left unattended, a site will become inaccessible and lose traffic, causing damage to its reputation in the process.
This article will help you understand what is “Error Establishing a Database Connection”, how to debug it in WordPress and explain what the possible causes for it are. Before we can jump into the first step of fixing this problem, however, we need to know exactly what this WordPress database error means.

Fortunately, this error message doesn’t appear on the front-end as long as the cache of your website is available. However, this WordPress database connection error blocks your access to the WordPress dashboard. With that in mind, it’s essential to determine what causes this error and fix that accordingly.
Keep reading to the next section to find out various possible reasons triggering this database connection in WordPress error.
How to Fix the WordPress “Error Establishing a Database Connection” in 6 Methods
Below are the six most common solutions for fixing the WordPress “Error Establishing a Database Connection” error. Before you start dealing with the error, make sure to create a backup of your site. If things go wrong, you can use it to restore your site.
1. Make Sure Your Domain Is Pointing to Your Host Provider
- Difficulty: Easy
- Success rate: Medium
- Estimated time to fix: 1 minute
Switching to a new hosting provider will automatically move your files to the new host. However, if your domain is not pointing to your host where the database is hosted, it will cause database failure.
To do so, start by checking the nameservers through your hosting control panel and WHOIS lookup tool. Hostinger users can access the hPanel dashboard and go to Accounts -> Details to accomplish this. If both nameservers match each other – your domain is pointing correctly.
If the results show otherwise, change the nameservers at your domain registrar. Simply access your hosting dashboard to get a list of the nameservers and enter them into your domain registrar’s control panel.
Another option is to point your domain name via the A record. It’s a type of DNS record that assigns your domain to its correct IP address. Keep in mind that the A record only points to a static IP address.
To perform this alternative, find your current IP address or the A record value and replace them with the ones from your new web host. Do so by using a local computer console or an online DNS checker. Hostinger users can find the IP address through the hPanel on Hosting -> Manage.

In the example above, the website’s A record value is 123.4.567.89. If the value matches your new hosting IP address, your domain name has already been pointed correctly. Otherwise, you need to update it from your domain registrar’s control panel.
2. Check Your Database Server
- Difficulty: Easy
- Success rate: Medium
- Estimated time to fix: 1-2 minutes
The “Error Establishing a Database Connection” message can also appear on your WordPress site when your MySQL server is down. While many reasons can cause this error, usually, too many connections are the problem.
A database server has a maximum number of clients connected at a certain time.
When it reaches that maximum capacity, it might fail to handle more connections. For this reason, we recommend contacting your hosting provider to check your MySQL server.
If you host more than one site on the same server, you can also see if your MySQL server is down on those sites as well. Meanwhile, if you host a single site, use PHP to connect to MySQL and check if your WordPress database user has sufficient permission.
Navigate to your hosting control panel and access your public_html folder. There, create a new PHP file and name it whatever you want. In this example, we’re going to name the file test.php.

Paste the following code into the file.
Replace the database password and username with your credentials. Lastly, save this file to your website and access it through the web browser.

If it’s connected successfully, it means that your user has enough permissions, and something else is causing the “Error Establishing a Database Connection” message to appear.
Usually, a website on a shared server tends to experience database errors due to splitting resources. Performing website caching with plugins like W3 Total Cache or WP Rocket is a good way to reduce the load on your server.
3. Check the Database Login Credentials
- Difficulty: Medium
- Success rate: High
- Estimated time to fix: 7-10 minutes
The most common reason for the WordPress “Error Establishing a Database Connection” message is invalid login credentials. Usually, this happens after a WordPress site migration to a different hosting provider.
To fix this problem, check if the database login settings match with the ones stored in your wp-config.php file. You can access this file via an FTP client or the WordPress File Manager in your hosting control panel.
hPanel
The following troubleshooting steps will show you how to access the wp-config.php file via Hostinger’s File Manager. To start, access your hPanel dashboard, and go to Files -> File Manager.

Clicking on it will take you to a page containing a list of your site files. From there, navigate to your public_html directory and locate the wp-config.php file. Next, right-click on the file and select Edit.

This will open a set of database information and configurations. Find and take note of the following data:
- DB_NAME – database name
- DB_USER – username
- DB_PASSWORD – password
- DB_HOST – database host

After that, navigate back to your hPanel and go to Database -> MySQL Databases. There, check your current database information under the List of Current MySQL Databases And Users section.

If the login data in your wp-config.php file is different from the MySQL database settings, match them by modifying the wp-config file.
Then, edit these lines:
Once you’ve edited the file, refresh WordPress to see whether the “Error Establishing a Database Connection” on the website is now resolved. If the error still persists, the database password could still be false. In this case, you need to reset your MySQL password.
Simply head over to the List of Current MySQL Databases And Users section, click on your current database, and select Change Password.

After entering the new password, hit the Update button.

If your database username and password are correct, but you still receive the “error establishing a database connection” message, change your database host information in the wp-config.php file.
With WordPress, web hosting companies tend to use localhost as the database host. However, we recommend contacting your web hosting company to confirm your database host information.

If you have recently switched hosts, double-check the DB_HOST details. In most cases, localhost won’t change, but some web hosts use an IP Address or different URL.
cPanel
For cPanel users, the steps are more or less the same. To open your wp.config.php file, go to Files -> File Manager. Then, click on the public_html directory and locate the file.
Once you have the information, check whether the value of DB_NAME matches your database name through Databases -> phpMyAdmin.

On the left side of your window, you will see your database name along with information_schema. If the name matches the DB_NAME value on your wp-config.php file, then your database name is not causing the problem.

If the name doesn’t match, edit the value in wp-config.php directly using cPanel’s file manager.
However, if your database name is correct, but the error persists, the problem might be your database username and password. To fix the database credentials, create a new PHP file under your root directory.
Name the file as you please, for example, new-database-file.php.

Then, copy the following code:
Replace the values of ‘user’ and ‘password’ according to your database credentials. Next, test the file by accessing the following page on your browser: http://your-site-domain.com/new-database-file.php.
If your username and password are correct, the following window will appear on your screen:

Once your database is back to working properly, don’t forget to delete the file. However, if your database login credentials are wrong, this window will appear instead:

In this case, create a new database user through the Databases -> MySQL Databases menu. Enter your new database credentials and update the values on wp-config.php accordingly.
4. Fix the Corrupted Files
- Difficulty: Medium
- Effectivity level: High
- Estimated time to fix: 10-12 minutes
Besides corrupted databases, corrupted files can also be the reason behind “Error Establishing a Database Connection”
A faulty theme or plugin is one of the factors that cause file corruption. To identify which component is causing the error, check them separately. Your theme might be the problem if the error happens after activating a new one.
To resolve this problem, navigate to Appearance -> Themes on your WordPress dashboard and then switch to another theme.

If changing the theme doesn’t fix the “Error Establishing a Database Connection” problem, it might come from a corrupted plugin. In this case, try disabling all of your plugins and enabling them one by one to find the culprit.
Alternatively, you can deactivate all WordPress plugins by renaming the corresponding folder from your hosting control panel. Here’s how to do so.
hPanel
Go to the File Manager, open the public_html directory, and click on the wp_content folder. Then, rename the currently used plugins folder.

cPanel
Navigate to the File Manager menu on your cPanel dashboard. Click on public_html -> wp_content and locate the plugins folder. Right-click on the folder, then choose Rename.

Doing so will disable all of your plugins at once. The same troubleshooting steps also apply to disabling all WordPress themes. However, make sure not to disable both the themes and plugins at the same time as this will make it much harder to figure out the root of the problem.
If the error disappears after renaming the plugins folder, it means that one of the plugins is the issue.
Once you’ve regained access to your site’s back-end, restore the plugins folder to its original name. This way, all of the WordPress plugins will still be inactive, but you can activate each one from the admin area.
Important! Don’t forget to delete the WordPress theme or WordPress plugin that causes the error.
That said, if none of the steps above work, try re-uploading the core files onto your WordPress site. To do this, download a fresh version of WordPress.

When the download is complete, unzip the package. Inside the folder, delete the wp-content folder along with the wp-config-sample.php file.

After deleting them, open an FTP client and upload the remaining WordPress files onto your root folder. This should now safely overwrite all of the corrupted files on your server.
5. Repair the Database in WordPress
- Difficulty: Hard
- Success rate: High
- Estimated time to fix: 15-20 minutes
Another fault that may result in the “Error Establishing a Database Connection” in WordPress is a corrupted database. This can be caused by data failure from plugins or themes that are regularly added or removed.
You might have a corrupted database if your WordPress dashboard shows a message along the lines of “One or more database tables are unavailable. The database may need to be repaired.”
Fortunately, you can easily fix this problem by inserting the following function into the bottom of your wp-config.php file:
hPanel
Hostinger users can simply access the File Manager, go to the public_html folder, and edit the wp-config.php file.

Input the code, and don’t forget to save the changes. Next, go to http://www.your-site-domain.com/wp-admin/maint/repair.php on your browser.
There will be two options to repair your database – choose the one that fits you better.

After the repair process is over, check your WordPress site and see whether it’s back to normal. If so, go to your wp-config.php file and remove the function immediately. This prevents any website abuse as anyone can access the repair page without logging in.
cPanel
The same steps apply to cPanel users. Go to Files -> File Manager, open the root directory, then add the function above to the wp-config.php file.
Aside from editing the wp-config file, cPanel users can benefit from its built-in functionality to repair MySQL databases. Start by navigating to Databases -> MySQL Databases.

6. Create a New Database
- Difficulty: Hard
- Success rate: Medium
- Estimated time to fix: 15-20 minutes
If all of the methods above still yield no results, your database might be corrupted entirely and cannot be used anymore. In this case, you need to create a new MySQL database and user from your hosting control panel.
Once a new MySQL database is created, restore your website backup to ensure you don’t lose any essential website data.
hPanel
hPanel users can simply head over Databases and click MySQL Databases. On the top page, there is a section to create a new MySQL database and database user.

Enter your database name, username, and password, then click the Create button. Keep in mind that the database password should contain at least eight or more characters with uppercase and lowercase letters.
Once you’re done, the new database will appear on the List of Current MySQL Databases and Users. You can then manage the database and complete multiple tasks, such as creating a backup.

cPanel
On cPanel, go to Databases -> MySQL Databases. You will see the Create New Database section on top of the page. Start filling out your new database name and click Create Database.

The system will then add your new database to the list of Current Databases.

You can also create a new MySQL user from the same window and assign it to your new database. Users can perform various tasks, from creating new tables to updating rows, depending on the privileges.
Simply enter your new database username and password on the MySQL Users section, then click Create User.

Once a new user is created, scroll down to add the user to your new database.

Under the Modify Databases section, you will see two options to check or repair your database. To fix a corrupted database, choose the Repair Database option.

Wait for the process to finish and access your WordPress site to see whether the ”Error Establishing a Database Connection” message still appears.
Another alternative is repairing database tables from phpMyAdmin. To do so, simply go to Databases -> phpMyAdmin. Click on your database name and check all tables.

Then, click on the dropdown menu next to the Check all button and select the Repair table option.

It will trigger the REPAIR_TABLE statement to start and fix any corrupted table.
Bonus Methods to Fix WordPress “Error Establishing a Database Connection”
If none of the listed methods above work, there are some other steps you can take to fix “Error Establishing a Database Connection” in your WordPress website.
Update WordPress website URL
For those who have just recently moved to new web hosts, you might need to update your WordPress URLs. To do so, navigate to phpMyAdmin from your hosting dashboard. Then, access your WordPress database and click on the SQL tab.

Copy and paste the following code on the provided field:
Be sure to replace the values of ‘http://www.old-domain.com’ and ‘http://www.new-domain.com’ to your new and old website URLs accordingly. When you’re done, click the Go button.
Ask for help
We always recommend consulting with experts. Don’t hesitate to contact your web hosting customer service. They should be able to troubleshoot further the database connection problem you are having.
Here at Hostinger, we provide 24/7 live chat support that will assist you in fixing this problem. To contact our support team, just log in to your account and click on the purple button at the bottom right corner of your screen.
People who don’t have an account can submit questions to our General Inquiry channel.
Reboot the web server and restore backup
Users on dedicated servers, local servers, and VPS (Virtual Private Servers) can also reboot their servers. This will restart your web and database server, which may fix some errors. You can do this by using a root account and SSH clients, like Bitvise or Putty.
In other cases, you might need to restore a backup of both your database and WordPress files. Check to see if your web host has an automatic backup and download the most recent website backup available.
Reasons Behind “Error Establishing a Database Connection”
A few possible reasons that can cause the “Error Establishing a Database Connection” in WordPress include:
- Incorrect database login credentials. Keep in mind that the WordPress database uses different login information from your hosting panel. If there is any change to your database username and password, the old login information stored in your WordPress files will be invalid.
- Corrupted database. Issues like plugin failures and incompatible themes can cause corrupted database tables or missing information. When any database information is deleted or corrupted, it will result in an error.
- Database server error. Sometimes the problem comes from your web hosting end. For example, a sudden surge of traffic or permission issues can make your database unresponsive. This usually happens in a shared hosting environment where multiple websites use the same resources.
- Core files corruption. WordPress core files define how your site works and functions. Many reasons can lie behind corrupted files, from faulty plugins and themes to issues when transferring via an FTP client. When modified incorrectly, the core files can also get corrupted and cause failure in the database.
If you see the following window on the back-end of your WordPress site, the problem likely comes from invalid login credentials.

However, if a different error message appears, then the cause might be a corrupted database or a traffic spike. Luckily, fixing this database error only takes a few steps – we’ve summarized below.
Conclusion
Getting the “Error Establishing a Database Connection” error on your WordPress website can be frustrating. The website won’t load, causing a risk of losing traffic and customers.
This database error occurs as a connection to the server cannot be established by the WordPress website. It might be caused by different reasons, such as incorrect login credentials in the wp-config.php file, corrupted files, or server overload.
Fortunately, there are several simple ways to solve this error:
- Point your domain to the correct host – make sure your A record matches your web host’s IP address.
- Verify your login credentials – match the login credentials in your wp-config.php file with the ones in your MySQL Database.
- Repair database – by inserting the define(‘WP_ALLOW_REPAIR’, true); function into the wp-config.php file.
- Fix the corrupted files – deactivate corrupt themes or plugins via your WordPress dashboard or download the latest version of WordPress and re-upload your core files.
- Check your MySQL server – create a new file containing the mysqli_connect function to check if your database user has enough permissions.
- Create a new database – start over with a new MySQL database and import a backup.
We hope this article has helped you fix the WordPress “Error Establishing a Database Connection” issue on your website. Identify the possible cause of this error, follow the steps accordingly, and you won’t have to worry about this error anymore.
Suggested Reading

Nabilla is a website hosting and development enthusiast. She loves to share her knowledge with others in order to help them grow their online presence. When she’s not busy writing, Nabilla enjoys exploring nature and going on adventures. She is passionate about helping people achieve their online goals.
How to Fix the Error Establishing a Database Connection in WordPress
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.
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 could be due to a missing or individually corrupted table, or 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 fixing things on your WordPress site, no matter how tech-savvy you think you are.
You can use a popular WordPress backup plugin such as UpdraftPlus to backup your files and database. Once you have a successful backup, it is time to troubleshoot your database connection issues.
1. Check Your Database Login 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.
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.
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 are correct, then you may want to ensure 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. Check if Your Database Server is Down
The “Error Establishing a Database Connection” message can also appear on your WordPress site when your MySQL server is down. While many reasons can cause this error, usually, too many connections are the problem.
A database server has a maximum number of clients connected at a certain time.
When it reaches that maximum capacity, it might fail to handle more connections. For this reason, we recommend contacting your hosting provider to check your MySQL server.
If you host more than one site on the same server, you can also see if your MySQL server is down on those sites as well. Meanwhile, if you host a single site, use PHP to connect to MySQL and check if your WordPress database user has sufficient permission.
4. Fix the Corrupted Files
Besides corrupted databases, corrupted files can also be the reason behind “Error Establishing a Database Connection”
A faulty theme or plugin is one of the factors that cause file corruption. To identify which component is causing the error, check them separately. Your theme might be the problem if the error happens after activating a new one.
If changing the theme doesn’t fix the “Error Establishing a Database Connection” problem, it might come from a corrupted plugin. In this case, try disabling all of your plugins and enabling them one by one to find the culprit.
5. Repair the Database in WordPress
Another fault that may result in the “Error Establishing a Database Connection” in WordPress is a corrupted database. This can be caused by data failure from plugins or themes that are regularly added or removed.
You might have a corrupted database if your WordPress dashboard shows a message along the lines of “One or more database tables are unavailable. The database may need to be repaired.”
Fortunately, you can easily fix this problem by inserting the following function into the bottom of your wp-config.php file:
6. Create a New Database
If all of the above methods still yield no results, your database might be corrupted and cannot be used anymore. In this case, you need to create a new MySQL database and user from your hosting control panel.
Once a new MySQL database is created, restore your website backup to ensure you don’t lose any essential website data.
Summary
As you can see, there are quite a few ways to fix the “error establishing a database connection” in WordPress. The most common is 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.
Like what you’ve read? Hit the clap button and share this with your friends.
Ошибка установки соединения с базой данных 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 и добавьте в него такое содержимое:
Затем обновите конфигурацию сервисов:
Мы не вносили изменения в основной файл юнита потому, что он может быть перезаписан при обновлении, и все наши настройки пропадут, такой путь более безопасный. Проверить применилась ли конфигурация вы можете командой:
systemctl show mariadb

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

Но на самом деле, ошибка установки соединения с базой данных довольно распространена.
Понимание проблемы
WordPress использует две основные технологии: PHP и MySQL.
- PHP – это язык программирования. Файлы ядра WordPress написаны на нем.
- MySQL – это система управления базами данных (СУБД). WordPress использует базу данных MySQL для хранения содержимого сайта: записи, страницы, а заголовок сайта, макет виджетов и т. д.
Рассматриваемая в этой статье ошибка возникает, когда WordPress не может получить доступ к информации в базе данных с помощью команд PHP. Когда это происходит, WordPress выводит сообщение «Ошибка при установлении соединения с базой данных».
Несколько причин, из-за которых возникает эта ошибка:
- Неверные учетные данные для входа . Если пароль и изменились, WordPress не сможет получать информацию из базы данных.
- Поврежденные файлы WordPress . Это может возникать при обновлении плагинов, темы оформления и самого WordPress.
- Поврежденная база данных . Например, если вредоносный плагин повредил базу данных изнутри. А также вследствие хакерской атаки, сбоем в теме и т.д.
- Сервер базы данных не работает .
- Большой объем трафика . Из-за этого база данных не может отвечать на запросы. Например, если один из ваших постов стал «вирусным», и одновременно множество пользователей пытаются зайти на ваш сайт.
Как исправить ошибку “error establishing a database connection”
Сначала порекомендую путь, который быстро решит проблему. Затем я буду копать глубже.
Шаг 1: Свяжитесь со своим хостинг-провайдером

Если ваш сайт работал минуту назад, а сейчас он недоступен, то ошибка может произойти на стороне хостинга. Качественные хостинги предлагают быструю поддержку через чат.
В нем расскажите, что у вас возникла ошибка “error establishing a database connection” и спросите:
- работает ли сервер базы данных;
- нет ли сейчас на сервере скачков активности или трафика.
Служба поддержки хостера сообщит, в порядке ли ваша база данных и есть ли подозрительные действия на сервере.
Если неисправность возникла не на стороне сервера, перейдите к шагу 2.
Шаг 2: Проверьте, не были ли повреждены файлы плагинов или тем
Например, может быть, вы обновили плагин или тему , и все рухнуло. Или подключили сайт к внешнему сервису, отредактировали файлы вручную. Если вы этого не делали, пропустите этот шаг.
Что можно сделать:
- Подключитесь к хостингу через FTP. Вы можете сделать это с помощью бесплатного инструмента FileZilla .
Чтобы подключиться, необходимо ввести логин и пароль к вашему FTP- аккаунту. Самый простой способ получить их — это поискать первые электронные письма, которые вы получили от провайдера. А также запросить их у службы поддержки хостера.
Затем подключитесь к серверу и перейдите в корневую папку WordPress. Обычно она называется «public_html» или «www».
Если видите перед собой подпапки типа «wp-content» и «wp-admin», то вы находитесь в корне WordPress. Пример:

- Зайдите в папку «wp-content» и переименуйте папку «plugins» . Задайте любое другое имя:

- Вернитесь на сайт и проверьте, не решилась ли проблема.
Если ошибка устранена, то теперь вы знаете, что она была вызвана каким-то плагином. Вернитесь на сервер, переименуйте папку обратно в «plugins». Зайдите в нее и измените имена папок отдельных плагинов. Самый простой способ сделать это — добавить в конце имени нижнее подчеркивание: «_»

Продолжайте, пока не выясните, когда ошибка возникает, а когда нет. Как только вы сузите круг поиска до одного конкретного плагина, удалите его или найдите решение проблемы в интернете.
- Если ошибка сохраняется и после переименования папки «plugins», выполните тот же процесс для папки «themes».
- Если это не поможет, переименуйте обе папки обратно в «plugins» и «themes». Ошибка связана с чем-то другим.
Шаг 3: Проверьте, не была ли повреждена база данных
- Зайдите в панель управления WordPress — YOURSITE.com/wp-admin
Если вы видите ту же ошибку: «error establishing a database connection», пропустите шаг.
- Обратите внимание на то, что WordPress предлагает вам сделать. Один из вариантов:

Если увидите сообщение, начинающееся с » One or more database tables are unavailable […]” . Это означает, что нужно «отремонтировать» базу данных.
Сначала подключитесь к сайту через FTP. Перейдите в корневой каталог WordPress и загрузите на свой компьютер файл «wp-config.php».
Откройте его в текстовом редакторе и строку в конце (прямо перед » That’s all, stop editing” ):
Теперь загрузите файл обратно на сайт (через FTP). Перейдите по адресу YOURSITE.com/wp-admin/maint/repair.php
Вот что вы должны увидеть:

Нажмите любую из кнопок. После завершения автоматического восстановления вернитесь на сайт и посмотрите, исправлена ли ошибка.
Если ошибки нет, отлично! Но вам все равно нужно вернуть файл «wp-config.php» в его предыдущее состояние. Удалите строку, которую добавили, и повторно загрузите файл.
Если ошибка не устранена, перейдите к следующему шагу.
Шаг 4. Проверьте учетные данные подключения к базе данных.
Если пароль и логин от базы данных изменились, возникает ошибка “error establishing a database connection”! Ее Исправление выполняется в файле wp-config.php. Я говорю об этих строках:
Они содержат всю информацию, необходимую WordPress для подключения к базе данных. Если что-то в ней неверно, соединение не будет установлено.
Скопируйте указанные выше строки, вставьте в окно чата и спросите у службы поддержки хостинга, верны ли данные для подключения к вашей базе данных. Если нет, то специалист предоставит корректные значения для авторизации.
Скопируйте новые учетные данные и поместите их в файл wp-config.php.
Повторно загрузите файл через FTP. После этого вернитесь на сайт и посмотрите, исправлена ли ошибка. Если нет, переходим к последнему шагу.
Шаг 5: Восстановите файлы WordPress
Файлы ядра WordPress могут быть повреждены по ряду причин. Но можно восстановить стандартные файлы WordPress, используемые по умолчанию. Самый простой способ сделать это – загрузить чистую версию движка с сайта WordPress.org и установить ее поверх той, которая есть у вас.
Перейдите по этой ссылке и загрузите последнюю версию WordPress. Распакуйте архив и удалите из него папку «wp-content».
Далее подключитесь к своему сайту через FTP, перейдите в корень WordPress, загрузите новые файлы CMS. Перезапишите существующие файлы.

Когда загрузка будет завершена, вернитесь на свой сайт и проверьте результат. Если это не поможет, обратитесь еще раз в службу поддержки хостинга. Расскажите им обо всем, что вы сделали, и попросите помочь.
Как избежать возникновения этой ошибки в будущем?
Идеального способа защиты сайта от ошибок соединения с базой данных нет. Но вероятность возникновения этих проблем можно минимизировать, придерживаясь некоторых правил:
- Работайте только с хостингами, которые оптимизировали свои серверы для работы с WordPress. Благодаря этому вы всегда сможете рассчитывать на квалифицированную поддержку помощь.
- Установите простой плагин резервного копирования, такой как UpdraftPlus . Благодаря ему у вас всегда будет рабочая резервная копия WordPress.
Я надеюсь, что это руководство вам поможет.
Вадим Дворников автор-переводчик статьи « How to Fix “Error Establishing a Database Connection” in WordPress »