Error establishing a database connection localhost

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

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

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?

Это сообщение об ошибке выглядит довольно серьезно.

Во-первых, перестаньте паниковать!

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

  • Понимание проблемы
  • Как исправить ошибку “error establishing a database connection”
    • Шаг 1: Свяжитесь со своим хостинг-провайдером
    • Шаг 2: Проверьте, не были ли повреждены файлы плагинов или тем
    • Шаг 3: Проверьте, не была ли повреждена база данных
    • Шаг 4. Проверьте учетные данные подключения к базе данных.
    • Шаг 5: Восстановите файлы WordPress
  • Как избежать возникновения этой ошибки в будущем?

WordPress использует две основные технологии: PHP и MySQL.

  • PHP – это язык программирования. Файлы ядра WordPress написаны на нем.
  • MySQL – это система управления базами данных (СУБД). WordPress использует базу данных MySQL для хранения содержимого сайта: записи, страницы, а заголовок сайта, макет виджетов и т. д.

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

Несколько причин, из-за которых возникает эта ошибка:

  • Неверные учетные данные для входа. Если пароль и изменились, WordPress не сможет получать информацию из базы данных.
  • Поврежденные файлы WordPress. Это может возникать при обновлении плагинов, темы оформления и самого WordPress.
  • Поврежденная база данных. Например, если вредоносный плагин повредил базу данных изнутри. А также вследствие хакерской атаки, сбоем в теме и т.д.
  • Сервер базы данных не работает.
  • Большой объем трафика. Из-за этого база данных не может отвечать на запросы. Например, если один из ваших постов стал «вирусным», и одновременно множество пользователей пытаются зайти на ваш сайт.

Сначала порекомендую путь, который быстро решит проблему. Затем я буду копать глубже.

Шаг 1: Свяжитесь со своим хостинг-провайдером

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

В нем расскажите, что у вас возникла ошибка “error establishing a database connection” и спросите:

  • работает ли сервер базы данных;
  • нет ли сейчас на сервере скачков активности или трафика.

Служба поддержки хостера сообщит, в порядке ли ваша база данных и есть ли подозрительные действия на сервере.

Если неисправность возникла не на стороне сервера, перейдите к шагу 2.

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

Что можно сделать:

  • Подключитесь к хостингу через FTP. Вы можете сделать это с помощью бесплатного инструмента FileZilla.

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

Затем подключитесь к серверу и перейдите в корневую папку WordPress. Обычно она называется «public_html» или «www».

Если видите перед собой подпапки типа «wp-content» и «wp-admin», то вы находитесь в корне WordPress. Пример:

Шаг 2: Проверьте, не были ли повреждены файлы плагинов или тем

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

Шаг 2: Проверьте, не были ли повреждены файлы плагинов или тем - 2

  • Вернитесь на сайт и проверьте, не решилась ли проблема.

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

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

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

Если вы видите ту же ошибку: «error establishing a database connection», пропустите шаг.

  • Обратите внимание на то, что WordPress предлагает вам сделать. Один из вариантов:

Шаг 3: Проверьте, не была ли повреждена база данных

Если увидите сообщение, начинающееся с «One or more database tables are unavailable […]”. Это означает, что нужно «отремонтировать» базу данных.

Сначала подключитесь к сайту через FTP. Перейдите в корневой каталог WordPress и загрузите на свой компьютер файл «wp-config.php».

Откройте его в текстовом редакторе и строку в конце (прямо перед «That’s all, stop editing”):

define('WP_ALLOW_REPAIR', true);

Теперь загрузите файл обратно на сайт (через FTP). Перейдите по адресу YOURSITE.com/wp-admin/maint/repair.php

Вот что вы должны увидеть:

Шаг 3: Проверьте, не была ли повреждена база данных - 2

Нажмите любую из кнопок. После завершения автоматического восстановления вернитесь на сайт и посмотрите, исправлена ли ошибка.

Если ошибки нет, отлично! Но вам все равно нужно вернуть файл «wp-config.php» в его предыдущее состояние. Удалите строку, которую добавили, и повторно загрузите файл.

Если ошибка не устранена, перейдите к следующему шагу.

Если пароль и логин от базы данных изменились, возникает ошибка “error establishing a database connection”! Ее Исправление выполняется в файле wp-config.php. Я говорю об этих строках:

define('DB_NAME', 'some_db');
define('DB_USER', 'some_username');
define('DB_PASSWORD', 'some_pass');
define('DB_HOST', 'localhost');

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

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

Скопируйте новые учетные данные и поместите их в файл wp-config.php.

define('DB_NAME', 'some_db'); /* это имя базы данных WordPress */
define('DB_USER', 'some_username');
define('DB_PASSWORD', 'some_pass');
define('DB_HOST', 'localhost'); /* это веб-адрес сервера вашей базы данных */

Повторно загрузите файл через FTP. После этого вернитесь на сайт и посмотрите, исправлена ​​ли ошибка. Если нет, переходим к последнему шагу.

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

Перейдите по этой ссылке и загрузите последнюю версию WordPress. Распакуйте архив и удалите из него папку «wp-content».

Далее подключитесь к своему сайту через FTP, перейдите в корень WordPress, загрузите новые файлы CMS. Перезапишите существующие файлы.

Шаг 5: Восстановите файлы WordPress

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

Идеального способа защиты сайта от ошибок соединения с базой данных нет. Но вероятность возникновения этих проблем можно минимизировать, придерживаясь некоторых правил:

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

Я надеюсь, что это руководство вам поможет.

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

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

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

Fixing the database connection error in WordPress

What Causes Error Establishing a Database Connection in WordPress?

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

Database connection error in WordPress

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

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

WordPress needs the following information for connecting to the database:

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

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

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

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

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

Video Tutorial

Subscribe to WPBeginner

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

1. Check Your WordPress Database Credentials

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

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

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

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

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'database_name_here' );
/** MySQL database username */
define( 'DB_USER', 'username_here' );
/** MySQL database password */
define( 'DB_PASSWORD', 'password_here' );
/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

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

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

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

Database information

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

Database name and username

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

Changing database user password

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

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

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

2. Check Your Database Host Information

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

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

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

3. Repair WordPress Database

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

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

define('WP_ALLOW_REPAIR', true);

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

Repair WordPress database

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

4. Check if Your Database Server is Down

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

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

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

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

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

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

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

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

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

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

Other Solutions That Have Worked for Users

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

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

1. Update WordPress Site URL

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

Running SQL in phpMyAdmin

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

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

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

2. Rebooting Web Server

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

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

3. Ask for help

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

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

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

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

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

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.

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

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

Содержание

  1. Перевод на русский язык Error establishing a database connection и почему она возникает
  2. Проверка синхронизации базы данных и CMS в wp-config
  3. Запуск восстановления
  4. Что делать после восстановления – сравнение префиксов
  5. Как исправить через восстановление MySQL
  6. Появление error establishing a database connection после установки плагинов
  7. Backup файлов и базы данных
  8. Как устранить если ничего не помогло

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

  • Открыли файл wp-config.php, нарушили комбинацию логина и пароля подключения. Самая распространенная ошибка, новички любят смотреть и менять файлы движка
  • Установка нового плагина. Обычно относится к тем, которые меняют текстовую часть сайта — записи, комментарии, то есть элементы содержащиеся в базе данных MySQL
  • Работы на сервере, редко, но могут выявить ошибку Error establishing a database connection. В основном это аварийные изменения
  • Переход на другой хостинг. Специалисты хостинга при переносе не проверили работу сайта и отдали вам не работающий ресурс. Проблема редкая, но имеет место, потому существует человеческий фактор
  • Много посетителей или DDoS атака. Каждый хостинг заботится о клиентах, предупреждает такие ситуации, но если наплыв большой, то сервер может упасть
  • Разрыв связи после бэкапа, ошибка возникающая из-за выбора не правильного времени восстановления файлов и DB. Есть универсальный метод, описанный далее

Проверка синхронизации базы данных и CMS в wp-config

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

Вошли в корневую папку сайта там где каталоги wp-admin и wp-content. Ищем файл wp-config.php, открываем его с помощью правой кнопки мыши, выбираем Просмотр/Правка.

Инструмент правки в файлзилле
Просмотр/Правка wp-config

Откроется программа для редактирования документов. Запомним несколько строк, а именно:

подключение DB в документе конфигурации
Строки в wp-config
  1. DB_NAME имя базы в нашем случае valent5k_wp3
  2. DB_USER пользователь, так же valent5k_wp3
  3. DB_PASSWORD пароль от подключения
  4. DB_HOST адрес сервера или хоста, по умолчанию localhost, но бывает и другие значения

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

Сверяем данные
Запоминаем данные

Если эти три параметра совпадают с прописанными из wp–config, то двигаемся дальше, если нет то перезаписываем, в wp-config, на то что указано в панели Бегета. Теперь нажимаем на значок с двумя точками.

Кнопка чтобы задать новый пароль
Смена пароля

Вписываем пароль из wp-config в поле DB_PASSWORD, у нас juzPo7HP6 и нажимаем Изменить.

Задаем новый пароль
Изменение пароля БД

Теперь смотрим на сайт и смотрим все ли работает. План действий такой:

  • Открываем wp-config
  • Копируем конфигурацию подключения
  • Сверяем или обновляем доступы к базе данных на хостинге

Такая схема работает и с нарушениями на локальном сервере типа Open server, XAMPP, Laragon и им подобные. Для более наглядного представления процесса записал свое видео.

Запуск восстановления

Существует аварийный запуск (fix) восстановления контакта SQL и файлов стандартными средствами WordPress . По знакомой схеме открываем файл wp-config, в конец вставляем код.

define('WP_ALLOW_REPAIR', true);
Куда прописывать вызов восcтановления DB
Код восстановления WP

Не забываем сохранять изменения и закачивать обратно на хостинг через FileZilla.

Переходим по адресу site.ru/wp-admin/maint/repair.php где взамен site.ru доменное имя. Откроется страница на которой нажимаем Починить поврежденную базу данных.

Нажимаем починить
Кнопка Починить

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

Обработка и восстановление database
Результат работы

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

Что делать после восстановления – сравнение префиксов

Сравнение префиксов таблиц необходимо делать, чтобы перейти к следующему шагу расследования ошибки error establishing a database connection. Заходим в FileZilla опять в файл wp-config, и смотрим на строчку table_prefix.

Префикс баз в WP
Префикс в вордпрессе

Запоминаем и идем в PhpMyAdmin на хостинге, как туда заходить уже знаем. В списке баз находим соответствующую сайту, нажимаем значок для перехода в MySQL.

Загрузка панели PhpMyAdmin
Переход в PhpMyAdmin

Далее смотрим на префиксы таблиц, если они совпадают, то проблема не в этом идем дальше.

Проверка
Префикс в SQL

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

Как исправить через восстановление MySQL

В 90% случаев исправить SQL не даст результата, но попробовать стоит. Заходим в PHPMyAdmin. Отмечаем чекбоксы напротив всех таблиц, внизу выбираем из выпадающего списка Восстановить таблицу.

Восстановление БД

Восстановление DB через интерфейс MySQL

Начнется процесс восстановления, способ может помочь, но в далеко не всех случаях, ищите проблему в других местах.

Появление error establishing a database connection после установки плагинов

Если блог на WordPress заклинило после установки плагина и появилась надпись error establishing a database connection, то нужно удалить его, но как если войти в админку нет возможности? Ответ прост, идем в FileZilla и удаляем. Путь до папки с плагинами wp-content > plugins.

Расположение плагинов в ядре WP
Папка с плагинами

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

Backup файлов и базы данных

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

Единственный минус, что все изменения внесенные после даты восстановления сотрутся и придется проделывать действия заново. Заходим в BackUp в панели хостинга.

BackUp на хостинге
Раздел бэкапа

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

Загрузка старой версии
восстановление файлов WP

Переходим в раздел Базы данных, отмечаем соответствующую сайту, так же выбираем дату и жмем синюю стрелочку.

BackUp БД
Бекап БД

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

Как устранить если ничего не помогло

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

На крайний случай обратитесь к нам за помощью, что будет в наших силах сделаем. Я разобрал максимум решений ошибки Error establishing a database connection и решений, если есть дополнения, то жду в комментарии. Успехов.

Пожалуйста, оцените материал:

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.

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

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!

Updated on January 4, 2023

How to Fix Error Establishing a Database Connection in WordPress

WordPress error establishing a database connection

Table of Contents [TOC]

  • WordPress error establishing a database connection
  • What does error when establishing a database connection means?
    •  
    • What Causes wordpress error establishing a database connection?
      • ☑️ Incorrect Database login credentials in WP config
      • ☑️ Corrupted Database
      • ☑️ Compromised files in your WordPress Installation
      • ☑️ Database Server Issues
      • ☑️ WordPress database tables have been damaged
    •  How to Fix the Error Establishing a Database Connection?
      • ☑️ Check Your Database Login Credentials
      • ☑️ Improving Compromised Database:
      • ☑️Repair DataBase Using phpMyAdmin:
      • ☑️Fixing Corrupt Files:
      • ☑️ Fixing Issue with the Server:
  • Fix Error establishing a database connection localhost
  • Fix database connection error on VestaCP
    • How to prevent this in future?
  • Need Help?
    • Like this:
    • Related

If you getting error establishing a database connection after installing wordpress, your website is unable to connect to the WordPress database. Unable to establish a database connection is a serious error that prevents visitors from accessing your website.

Nothing can tremble a WordPress website owner than seeing a message like – Can’t login to wordpress Error establishing a Database Connection localhost . We all panic after noticing any type of failure that makes our WordPress website go down [eg: “This Account Has Been Suspended” – WordPress Down[Fix]]

 If you’re having trouble with WordPress and are unable to authenticate, here are some ways to fix the error with simple explanations. In this article, you will learn ❌ How to Fix Error Establishing a Database Connection in WordPress website and we will also discuss the major reasons for getting this error and how can we prevent it. 

Some other common wordpress errors you might want to read about are – Error 504 Gateway Timeout in WordPress, 405 Method Not Allowed Error, Error 404 Page Not Found In WordPress, White Screen of Death Error in WordPress, The link you followed has expired error in WordPress,Are you sure you want to do this Error WordPress,  503 Service Unavailable Error,

What does error when establishing a database connection means?

All relevant information about your WordPress sites such as post information, pages, plugin settings, and user information is kept in the database. WordPress connects to this database every time someone visits your website.

The database in question does not store media files (images and video) and basic files for plugins/themes such as index.php, wp-login.php, etc.

When someone visits your webpage, PHP executes the relevant code on the page and retrieves the information from the database, displaying it to the site visitor in the browser.

To successfully establish the connection, you need the following information:

This information can be found in the WordPress wp-config.php configuration file. If any of these settings are incorrect, WordPress will not be able to connect to the database.

In this case, the browser window will display the Database connection error notification.

Every bit of information present on your WordPress website is stored in your MYSQL database.  This includes your posts, pages, layout design, widgets, plugins themes etc. In simple words, every bit of information about your website is stored in your database.

When you get an error like this, it means your website is no longer communicating or has access to your database, and thus your entire website goes down.  As a result, no content is visible to the user. A blank white screen with a message ” connection is not working properly” is displayed whenever any user tries to connect to your website.

This is a kind of HTTP Error Code 500 which means ” Server error codes indicating that the request was accepted, but that an error on the server prevented the fulfillment of the request.”This same status code appears when there is an “internal server error“.

It essentially 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.

“200 Status Code which means “Everything is OK.” This is the code that is delivered when a web page or resource acts exactly the way it’s expected to.”

 fix-error-establishing-a-database-connection-in-wordpress

Related Issues – WordPress Stuck in Maintenance Mode | Parse Error Syntax Error Unexpected in WordPress

What Causes wordpress error establishing a database connection?

Here are a few common reasons explaining why this error exactly occurs on a WordPress website:

☑️ Incorrect Database login credentials in WP config

The most common reason for getting this kind of error is the incorrect database login credentials. There are no similar credentials for your WordPress website login and database login. A database login requires separate credentials which should be too strong to guess.  If there is any change in username or password, then WordPress will not be able to fetch any data from the database.

☑️ Corrupted Database

What if your database is corrupted? Yes, this could be the reason behind the error. We all have some plugins and themes of older versions and are no longer in use. But no one takes out time to deactivate or delete them. Now, this is how loopholes occur and let the hackers easily hack your website.

Another possibility could be an unsuccessful update of your WordPress database which includes missed plugins, themes or even failure in WordPress software update.

☑️ Compromised files in your WordPress Installation

This might be possible that your WordPress installation has certain corrupted files which are creating the error in connection with the database. Such files might be the loopholes or backdoors placed by the hackers in order to regain access to your website.

☑️ Database Server Issues

Your database server may have some issues which require quick resolving.  A number of things may go wrong with your database server like

  • the database being overloaded from a traffic
  • unresponsive database due to too many connections requests at one time. Though it is good for your website, it may create trouble.

This type of problem generally occurs due to shared hosting where a number of users are hosted on the same server.

☑️ WordPress database tables have been damaged

 How to Fix the Error Establishing a Database Connection?

Before initiating how to fix this database connection error, we recommend our readers to take a backup of your entire site along with the database. Make this a habit whenever you try to fix any error on your WordPress website.

There are a few plugins which automatically take a backup of your site every day so that you don’t need to have a manual setup every time you update your website or make any changes to it.

You can use WordPress backup plugins such as UpdraftPlus or Duplicator to backup both your files and your database.

📢 Now, let’s start with Troubleshooting .

☑️ Check Your Database Login Credentials

The major reason discovered behind the occurrence of this message is incorrect login credentials used to log in the database.  This happens for most of the people who have migrated to a new host. Make sure you are using right credentials.

The connection details for your WordPress site are stored in the wp-config.php file.

cPanel-File-Manager-public_html-Wp-Config.php

The file contains four important pieces of information that need to be correct for a successful database connection.

  1. The name of the database (“DB_NAME”)
  2. The login username (“DB_USER”)
  3. The login password (“DB_PASSWORD”)
  4. The database host (“DB_HOST”)

If any one of these values is incorrect, WordPress will not be able to connect to the database.

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

wpconfig

You can easily locate the wp-config.php file in the cPanel.  Simply click on “File Manager,” and browse to the root of your site, and right click to edit the file. There,  you have to verify all the input values with the ones on the server to ensure that they are correct.

 file manager

DB_Name: The first thing to verify is the database name. You can check it through cPanel dashboard. Login into phpMyAdmin and check out the name of your database.

When you click on your database name, a screen listing the names of the tables in the database will appear. Click on the “Browse” button next to the table named wp-options, and see if you find your site name and URL along with other settings.

If yes, and the name matches your wp-config entry, you have the right database. If the URL is right, but your wp-config file is wrong, change the name there to match the right database.

Next, verify the username and password. You can test it via two ways:

Create a PHP test file to verify whether the credentials from wp-config connect you to the database. Paste the following code:

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

Add database credentials to the new text file and save it.

Now, type the URL of the file into your browser and try it; you’ll either get the “Connected successfully” message or the “Could not connect” message.

If you didn’t find the username and password in the table, create a new one in the wp-options. Be sure to make changes in the wp-config file as well.

If you don’t know how to add anew user, follow these steps:

  1. Go to the cPanel and click on “MySQL Databases”.
  2. Scroll to the MySQL Users. from there, add anew user.
  3. Create a new username and password and create “Create User”.
  4. Now find “Add User to Database”. Select the username and password you just created, and click “Add”.
  5.  Also, update the wp-config file with the newly created credentials.

Check if now the error is resolved.

☑️ Improving Compromised Database:

If the error still persists, the database might be corrupted. The worst thing that can appear in a WordPress database is missing tables which happens if hundreds of tables are added or removed by new plugins.

This may result in “error establishing a database connection” message displayed on front end whereas ” One or more database tables are unavailable” on the back end.

It is important to note that WordPress has repair mode which you can turn on  Simply add the following to the bottom of your wp-config.php file.

define(‘WP_ALLOW_REPAIR’, true);

Later, browse to the following location on your WordPress site:

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

database-repair

You will then have the option to repair the database or repair and optimize the database. Since you are probably troubleshooting an interruption on your site, we recommend operating the repair database option as it is quicker.

Make sure to remove the line of code added to your wp-config.php file after executing the database repair.

You can also execute the repair of your database using cPanel.

☑️Repair DataBase Using phpMyAdmin:

corrupted-db-phpmyadmin-repair-table

In order to run the database repair from within phpMyAdmin, follow these steps:

  • Simply log in to phpMyAdmin,
  • Click on your database, and select all the tables.
  • Then from the drop-down click on “Repair table.” This is essentially just running the REPAIR TABLE command.

☑️Fixing Corrupt Files:

The second probable cause of getting this error is that your files might be corrupted. This may happen while sharing files through FTP which is not so secure and thus, a hacker can easily gain access to your files. This issue is necessary to fix as quick as possible.  Be sure to create a backup before cleaning up the corrupted files.

To do so, follow these steps:

  1. As we recommended, make a backup of your WordPress database manually.
  2. Now, download the latest version of WordPress from here and replace the older version with the latest one.
  3. Unzip the backup created and remove the corrupted files.  You’ll want to delete the wp-content folder, as well as the wp-config-sample.php file.
  4. Now, upload rest of the files to the updated version of WordPress through a secure sharing application i.e. SFTP.
  5. Clear out the browser cache. Now, again check if the error still occurs.

☑️ Fixing Issue with the Server:

We tried to fix every possibility leading to this error . But if nothing worked that means you need to check your hosting provider because it may be occurring due to an issue with the database server.

As we discussed earlier, if its the case where a number of concurrent connection are utilizing your database at the same time. This can slow down the speed or even lose connections with the database.

In order to minimize interaction with your WordPress database, you can use caching plugins like W3 Total Cache, WP Super Cache, Quick Cache etc.

And, if we talk about shared hosts utilizing same resources on servers, you can fix this problem with a high-performance best managed WordPress hosting, so that it is easy to handle large amounts of traffic to your WordPress sites.


Fix Error establishing a database connection localhost

This error means that your website files (on the webserver) cannot connect to your database (on the database server).

Navigate to http://localhost/phpmyadmin.

Click on ‘to create a new database’, and choose a name for your database.

Next, open up wp-config.php in the root of your WordPress folder, and update the four values shown below to reflect your new database.

Every website that connects to a database has a configuration file. This configuration file stores the following database credentials that allow you to connect.

  • Database username.
  • Database user password.
  • Database hostname.
  • Database name.

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

define('DB_NAME', 'case sensitive chosen db name');

/** MySQL database username */

define('DB_USER', 'root');

/** MySQL database password */

define('DB_PASSWORD', '');

/** MySQL hostname */

define('DB_HOST', 'localhost');

If the database login information was changed in the panel without updating the connection information in the site configuration file, your site cannot connect to the database.

Fix database connection error on VestaCP

Although VestaCP is a younger panel than cPanel, it also puts at your disposal a simple and intuitive interface to work with databases. Using it you will be able to fix the “Error establishing a connection to the database” WordPress error.

As with cPanel, start by reviewing the first three possible causes of the error:

  1. Database name is wrong
  2. Database username is wrong
  3. The user’s password is not correct

By default, VestaCP does not have a file manager like cPanel, but you have several options to access your web files and view the contents of wp-config.php. For example, if you have Optimized VPS you will have a file manager integrated into the panel; but even if that wasn’t the case, you could connect via FTP with a program like FileZilla, or use SSH

Whatever you do, access the contents of the wp-config.php file and check the database name, MySQL username, and password that are configured. For example, over SSH you would see something like this:

Fix database connection issue on VestaCP Although VestaCP is a younger panel than cPanel, it also puts at your disposal a simple and intuitive interface to work with databases. Using it you will be able to fix the “Error establishing a connection to the database” WordPress error. As with cPanel, start by reviewing the first three possible causes of the error: 1. Database name is wrong 2. Database username is wrong 3. The user's password is not correct By default, VestaCP does not have a file manager like cPanel, but you have several options to access your web files and view the contents of wp-config.php. For example, if you have Optimized VPS you will have a file manager integrated into the panel; but even if that wasn't the case, you could connect via FTP with a program like FileZilla, or use SSH Whatever you do, access the contents of the wp-config.php file and check the database name, MySQL username, and password that are configured. For example, over SSH you would see something like this: https://wbcomdesigns.com/wp-content/uploads/2017/09/image001.png Now you have to compare them with the correct ones. Within VestaCP go to the databases section, and click on “ Edit ” for the database you are going to use: https://cloudcone.com/docs/wp-content/uploads/sites/2/2017/07/vesta_createdb.jpg On this screen, you can simultaneously check that both the database name and the MySQL user you use in WordPress are correct, as well as change the user's password if necessary. If you see any data in the wp-config.php file that is not correct, correct it! 4. There is something wrong with the server name you have configured As in cPanel, in a VestaCP environment, it is normal that both the database and the application are on the same server, so the correct name for the database server would be “ localhost ”. But if you think that this is not your case, confirm it with the technical team of your hosting company, they will be able to guide you! 5. The user does not have the appropriate permissions on the database In VestaCP you will not encounter this problem! This panel does not allow you to create a MySQL user without assigning it to a database; This is a little less flexible than cPanel, but it also takes away headaches like this. 6. Database server not responding If you're sure everything else is ok, it's up to you to SSH into the server and runs some tests to make sure everything is ok.

Now you have to compare them with the correct ones. Within VestaCP go to the databases section, and click on “ Edit ” for the database you are going to use:

cpanel wordpress error establishing a database connection

On this screen, you can simultaneously check that both the database name and the MySQL user you use in WordPress are correct, as well as change the user’s password if necessary. If you see any data in the wp-config.php file that is not correct, correct it!

  1. There is something wrong with the server name you have configured

As in cPanel, in a VestaCP environment, it is normal that both the database and the application are on the same server, so the correct name for the database server would be “ localhost ”. But if you think that this is not your case, confirm it with the technical team of your hosting company, they will be able to guide you!

  1. The user does not have the appropriate permissions on the database

In VestaCP you will not encounter this problem! This panel does not allow you to create a MySQL user without assigning it to a database; This is a little less flexible than cPanel, but it also takes away headaches like this.

  1. Database server not responding

If you’re sure everything else is ok, it’s up to you to SSH into the server and runs some tests to make sure everything is ok.

How to prevent this in future?

In order to avoid any database connection error on your WordPress website, here are few steps:

  1. Quality & Secure WordPress web hosting. Work only with hosts that have optimized their platforms to work with WordPress.
  2. Make sure to create regular backups every time you update your site You can also install a simple backup plugin like UpdraftPlus that works automatically.
  3. Keep the plugins and themes updated.
  4. Delete the WordPress plugins or themes that are no longer in use and scan your wordpress themes & plugins for malware periodically
  5. Always keep your WordPress up-to-date with the latest versions.

Need Help?

Certainly. this error is a matter of concern for a WordPress site owner but we have outlined a few quick ways to fix this error.  And, if this does not resolve the issue with your website or you need an expert help, we are always here to assist you.

To get started contact us here. We hope this article helped you learn how to fix error establishing database connection in WordPress easily.

Other Popular WordPress Tutorials:

  • WordPress Malware Redirect Hack
  • How To Fix Backdoor In Hacked WordPress Site?
  • How To Fix “This Account Has Been Suspended” Error in WordPress Site?
  • Best WordPress Security Plugins in 2023
  • Parse Error: Syntax Error Unexpected in WordPress
  • WordPress Hacked – How to Secure Your Site in 2023 [Guide]
  • 26 Best WordPress Performance Plugins – Optimize Site Speed
  • How To Remove Pharma Hack From WordPress site?
  • Remove CoinHive Malware WordPress

Окт 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 beget
  • Error establishing a database connection apache
  • Error enospc no space left on device write
  • Error espcomm upload mem failed
  • Error es modules may not assign module exports or exports use esm export syntax instead