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 folderplugins_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
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
andwp-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:
- Log in to your website using your FTP program
- 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:
- 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.
- 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.
- Find the my.cnf file. On *nix systems this is usually in /etc/. On Windows system, Find the my.ini.
- Once found, open this in a simple text editor and find the [mysqld] section.
- 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.
- Save the file.
- Shutdown MySQL by typing
mysqlshutdown -u -p shutdown
. - 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
Это – один из худших кошмаров для владельца веб-сайтов. Вы вводите URL-адрес вашего сайта… однако вас приветствует не ваша главная страница, а нечто другое. Вместо этого вы видите пустой экран. Вне зависимости от того, по какой ссылке вы перешли, вас встречают зловещие слова «Error establishing a database connection».
Чем дольше ваш сайт будет лежать, тем больше трафика вы потеряете. А это означает потерянных подписчиков, клиентов, а также упущенный доход. Однако что вообще привело к такой ошибке? Что она означает? И, что самое важное, как исправить ее, чтобы вернуть свой сайт в нормальное состояние как можно быстрее?
В этой статье мы расскажем вам, что означает это сообщение об ошибке, что может вызывать его, а также посмотрим, как найти корень зла и исправить его.
Содержание
- Что означает «Error Establishing a Database Connection»?
- Что приводит к этой ошибке?
- Решение проблем с «Error Establishing a Database Connection»
- 1. Определяем, с чем произошла ошибка.
- 2. Проверяем учетные данные БД в wp-config
- 3.Все еще появляется ошибка?
Что означает «Error Establishing a Database Connection»?
Для начала давайте посмотрим на то, как WordPress отображает ваш сайт, и тогда станет ясно, почему эта ошибка настолько разрушительная. WordPress написан на PHP и MySQL. Вся информацию, которая составляет ваш сайт, хранится в базе данных MySQL, а PHP используется в WordPress для сохранения и получения этой информации из базы данных.
В целом, всякий раз, когда страница загружается на вашем сайте, она создается «на лету». Код PHP используется для того, чтобы получить доступ к базе данных MySQL и получить всю информацию, которая требуется для создания страницы. Одни PHP-запросы получают заголовок записи, другие – захватывают имя автора, третьи – берут дату публикации и т.д.
Вернемся к нашему сообщению об ошибке: «Error establishing a database connection». Оно означает, что по каким-то причинам PHP-код не смог соединиться с базой данной MySQL, чтобы получить информацию, которая требовалась для создания страницы.
Именно по этой причине на экране с ошибкой красуется лишь одно сообщение. Если вы не можете подключиться к базе данных, вы не знаете, что выводить на экран; нет никакой доступной информации о вашем сайте.
Что приводит к этой ошибке?
В то время как само сообщение об ошибке является достаточно ясным, причины, отвечающие за его появление, зачастую не совсем понятны.
Есть много разных причин, почему ваш сайт может иметь проблемы с подключением к вашей базе данных, однако их обычно можно разбить по трем категориям:
- Ваши учетные данные для входа в БД являются неверными. Ваша база данных использует отдельный логин и пароль. Если эти данные были недавно изменены, ваш сайт не сможет подключиться к БД, используя старые учетные данные.
- Ваша база данных была повреждена. Привести к такому печальному исходу могут самые разные причины, начиная с установки некачественного плагина и заканчивая ударом молнии в сервер (правда, это не самый распространенный вариант).
- Сервер, на котором расположена ваша БД, в данный момент не работает. Сервер с вашей базой данных может выйти из строя из-за каких-либо проблем или ошибок на стороне хостинг-компании. Также он может «лежать» из-за того, что на ваш сайт обрушился большой поток трафика, который сервер просто не смог обработать.
Таким образом, учитывая все возможные ситуации, как мы можем справиться с возникшей проблемой?
Решение проблем с «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-адрес).
Вы должны увидеть страницу, показанную выше, с двумя возможностями восстановления – «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 для доступа к вашей БД:
- Название БД (DB_NAME)
- Логин для входа (DB_USER)
- Пароль для входа (DB_PASSWORD)
- Хост базы данных (DB_HOST)
Если какое-либо из этих значений будет некорректным, WordPress не сможет подключиться к базе данных.
Проверить базу данных вне WordPress можно при помощи PHPMyAdmin – инструмента, который используется для редактирования базы данных MySQL. PHPMyAdmin включен во многие тарифные планы хостингов, и вы можете найти его в консоли cPanel.
Предупреждение: Будьте аккуратны при работе с PHPMyAdmin, поскольку этот инструмент ведет прямую работу с базой данных.
Как только вы войдете в PHPMyAdmin, вы увидите список баз данных на вашем сервере. Щелкните по той из них, которая будет соответствовать названию БД в файле wp-config (значение DB_NAME).
Не видите ни одной базы данных? В таком случае обратитесь к вашему хостингу, поскольку, скорее всего, проблема связана с вашим сервером.
После щелчка по названию базы данных вы увидите основной экран, содержащий названия таблиц вашей БД. Чтобы убедиться в том, что это – корректная БД, вы можете найти таблицу под названием wp_options и щелкнуть по опции Browse рядом с ней. Вы должны увидеть название вашего сайта, URL, а также все основные настройки. Теперь вы знаете, ту ли базу данных вы открыли. Если нет, то настройте ее должным образом в wp-config.
Давайте теперь проверим логин и пароль.
Есть несколько способов проверить их. Я предложу вам два варианта.
- Вы можете создать простой .php файл для тестирования того, сможете ли вы подключиться к вашей базе данных с учетными данными из файла wp-config
- Вы можете создать нового пользователя с паролем, и обновить файл 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
Ни для кого не секрет, что большинство платформ для создания веб-сайтов, и в том числе такая популярная платформа, как 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, то сможете сразу же узнать о возможных проблемах. Надеюсь, эта информация была полезной для вас.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
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.
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.
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.
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.
Below that you will find the database users and links to change the 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
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.
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 at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience building WordPress websites. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.
Распространённая неисправность у новичков в работе с wordpress — error establishing a database connection. В статье разберем причины, следствия, пути исправления.
Перевод на русский и ошибки в cms wordpress
Точный перевод «Ошибка установки соединения с базой данных», то есть файлы и mysql (контентная часть) не соединяются.
Появление надписи в wordpress является следствием действий администратора, неожиданно она не появится. Существует несколько причин:
- Залез в wp-config.php. Незнание начинающих пользователей, что wp-config управляет настройкой связи, менять его категорически не рекомендуется.
- Плохие плагины. Установка нового «крутого» дополнения, которое посоветовал «знакомый» блоггер, «разбирающийся» в wordpress. Если поставили плагин и блог выдал error establishing a database connection, то удаляйте через FTP и всё станет на свои места.
- Хостинг проводит плановые или аварийные работы. Стандартно раз в месяц, ничего странного в этом нет, профилактика, ремонт нужен всяком оборудованию.
- Новая тема (шаблон)
- Переезд на другой хостинг. Проблема возникает если специалисты нового хостинга криво перенесли компоненты и не проверили работоспособность.
- Много посетителей. Перегруз сервера может прервать соединение, поэтому при возникновении перебоев, задумайтесь о переходе на более мощный тарифный план.
Главная причина — кривые руки, не знание куда человек заходит и что делает, удаление знака «;» может привести к поломке.
Решение error establishing a database connection будем вести в порядке, представленном выше.
Как исправить wp-config вручную
На нашей практике таких случаев было 4 штуки. Человек захотел прописать прямой доступ, например hyper cash, не туда вставил код, соответственно сайт заклинило. Пути решения таковы:
- Вернуть wp-config в первоначальный вид
- Если вернуть невозможно, то делаем backup через админпанель хостинга.
- Если после бэкапа ничего не произошло, то пишите в поддержку хостера.
Если хотим разобраться сами, то сравниваем подключение у хостера и в файлах движка. Рассмотрим на примере ISP manedger. Заходим в панель, находим «базы данных», в нашем примере «kras-net» — имя, адрес подключения — localhost, запоминаем.
Заходим (двойное нажатие ЛКМ), откроется панель управления доступами. Находим вверху логин и пароль, так же запоминаем.
Далее любым методом подключаемся к сайту (можно ftp или стандартный файловый менеджер), и в корне находим wp-config.php. Если работаем с FileZilla нажимаем правой кнопкой мыши и выбираем «просмотр/правка»
Откроется редактор по умолчанию для php, в первых строчках найдёте прописанные доступы, которые сравниваем с ранее записанными.
Если совпадает, то переходим к другому методу восстановления доступа.
Что значит запуск восстановления
Процедура восстановления проводиться только после создания полной резервной копии.
Для запуска восстановления в том же wp-config в самом конце вводим (не забываем сохранить):
<a href="#Step-2-Checking-database-connection-settings-in-wp-configphp">
Вводим url адрес в браузер site.ru/wp-admin/maint/repair.php и проводим процедуру, нажатием «починить базу данных». Оптимизация процесс не быстрый, его лучше совершают плагины.
Обязательно после проведения операции, удалить код из wp-config.php, иначе он становиться публичным. Любой робот может просканировать и украсть логин с паролем.
Сравнение префикса wp
После всех манипуляций, остаётся сравнить префиксы wp таблиц. В том же wp-config находим строчку table_prefix.
И одновременно заходим в phpmyadmin на хостинге, и смотрим префиксы mysql в левом столбце.
Если есть совпадения и error establishing a database connection не пропадает, то проблема кроется глубже, переходим к следующим действиям.
Что делать с некачественными плагинами
Чаще выдают неисправность плагины, изменяющие статьи или комментарии (то есть сам текст). Через админпанель удалить не получится, остаётся два пути:
- Переименовываем папку plugins. Делаем чтобы wordpress перестал их воспринимать. Если сработало и сайт открывается, то удаляйте плагины по одному.
- Бекап файлов за прошедший день
Любую новую тему и плагин пробуйте на тестовом ресурсе, почти у всех хостеров есть бесплатные поддомены, на них можно сделать точную копию основного (само собой без текстов) и тестировать новинки.
Плановые и аварийные работы
Если вы или сотрудники ничего не делали, то пишите в поддержку хостинга. В 95% случаев они подтвердят что делают работы, ждите, обычно час-два и ресурс заработает.
Новый шаблон
В редких случая причиной является некорректная тема (шаблон), как и с плагинами путей будет три, FTP, менеджер файлов или поддержка.
Переезд сайта
Переезд ресурса на другой хостинг процедура быстрая и безболезненная если говорить про wordpress. Запрос в поддержку даст ответ, на 100% решение, потому что косяк с их стороны. Не пытайтесь наладить, исправлять нужно им.
В итоге главной причиной является потеря связи файлов с базами, все выше описанные приёмы, помогут на 150% вернуть блог к жизни и убрать error establishing a database connection навсегда.
Нажмите, пожалуйста, на одну из кнопок, чтобы узнать понравилась статья или нет.