Você está vendo o aviso “Erro ao estabelecer uma conexão com o banco de dados” no WordPress?
Esse é um erro fatal que torna seu site inacessível aos usuários. Ele ocorre quando o WordPress não consegue estabelecer uma conexão com o banco de dados. Como vários fatores podem afetar essa conexão, o erro pode ser um pouco difícil de solucionar para iniciantes.
Neste artigo, mostraremos como corrigir facilmente o “Erro ao estabelecer uma conexão com o banco de dados” em seu site WordPress, passo a passo.
![make-money-of-passive-income-every-month-in-post Fix the Error Establishing a Database Connection in WordPress](https://www.wpbeginner.com/wp-content/uploads/2020/01/fix-the-error-establishing-a-database-connection-og.png)
Qual é a causa do erro ao estabelecer uma conexão com o banco de dados no WordPress?
Um banco de dados é um software que facilita o armazenamento, a organização e a recuperação de dados de outro software.
Como um sistema de gerenciamento de conteúdo, o WordPress usa um banco de dados para armazenar todo o seu conteúdo e outros dados do site. Em seguida, ele se conecta ao banco de dados sempre que alguém visita seu site.
O WordPress precisa das seguintes informações para se conectar ao banco de dados:
- Seu nome de banco de dados
- Nome de usuário e senha do banco de dados
- Servidor de banco de dados
Essas informações são armazenadas em seu arquivo de configuração do WordPress, chamado wp-config.php.
Se alguma dessas informações estiver incorreta, o WordPress não conseguirá se conectar ao seu servidor de banco de dados e você verá o erro “Error establishing a database connection” (Erro ao estabelecer uma conexão com o banco de dados).
![6 melhores softwares de discagem automática para pequenas empresas em 2024 (comparados) Database connection error in WordPress](https://www.wpbeginner.com/wp-content/uploads/2020/01/dbconnectionerrorwp-1.png)
Esse é um dos erros mais comuns do WordPress. Além das credenciais incorretas, esse erro também pode aparecer se o servidor do banco de dados estiver inativo ou se os arquivos do banco de dados estiverem corrompidos.
Dito isso, vamos dar uma olhada em como corrigir o problema “Erro ao estabelecer conexão com o banco de dados” no WordPress com uma solução de problemas passo a passo.
1. Verifique as credenciais do banco de dados do WordPress
O motivo mais comum para o erro de conexão com o banco de dados são as credenciais incorretas. Se você mudou recentemente seu site do WordPress para um novo host, provavelmente esse é o problema.
Suas credenciais de banco de dados do WordPress são armazenadas no arquivo wp-config.php. Esse é o arquivo de configuração do WordPress que contém configurações importantes, inclusive informações sobre o banco de dados.
Se você nunca editou um arquivo wp-config.php antes, dê uma olhada no nosso guia para iniciantes sobre como editar o arquivo wp-config.php para obter mais instruções.
Você procurará as seguintes linhas no arquivo 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' );
Aqui, você deve se certificar de que as informações sobre o nome do banco de dados, o nome de usuário, a senha e o host do banco de dados estejam corretas.
Você pode confirmar essas informações no painel da sua conta de hospedagem do WordPress. Para este tutorial, usaremos o Bluehost, mas o processo também será semelhante para outros painéis de hospedagem.
Ao fazer login, clique na guia “Website” na coluna da esquerda e, em seguida, mude para a guia “Advanced” (Avançado). Em seguida, role para baixo até a seção “Database” (Banco de dados) e clique no botão “Manage” (Gerenciar) ao lado dela.
![formidable-forms-field-label-min Click the Manage button next to the Database section](https://www.wpbeginner.com/wp-content/uploads/2020/01/click-manage-button-next-to-database-1.png)
Isso abrirá a página Bancos de dados MySQL no cPanel em uma nova janela.
Aqui, você pode encontrar o nome do banco de dados e o nome de usuário na seção “Current Database” (Banco de dados atual). Não se esqueça de copiar e colar esses detalhes em um bloco de notas para poder adicioná-los ao arquivo wp-config.
![bea-style-min Find your database name and username in the Current Databases section](https://www.wpbeginner.com/wp-content/uploads/2020/01/find-database-name-and-username-2.png)
Em seguida, role para baixo até a seção “Current Users” (Usuários atuais), onde você pode clicar no link “Change Password” (Alterar senha) ao lado do nome do seu banco de dados.
Isso o levará a uma nova tela, na qual você poderá alterar a senha do banco de dados de acordo com sua preferência.
![formidable-forms-create-blank-form-min Change your database password](https://www.wpbeginner.com/wp-content/uploads/2020/01/change-database-password-1.png)
Depois de confirmar todos os detalhes do banco de dados, você poderá alterar essas informações no arquivo wp-config.php, se necessário.
Depois disso, tente visitar seu site novamente para ver se o erro de conexão com o banco de dados desapareceu.
Se você ainda puder ver o erro, isso significa que algo mais está errado.
2. Verifique as informações do host do banco de dados
Se tiver certeza de que as informações de nome do banco de dados, nome de usuário e senha estão corretas, certifique-se de que está usando as informações corretas do host do banco de dados.
A maioria das empresas de hospedagem WordPress usa o localhost como seu host de banco de dados. No entanto, algumas empresas de hospedagem gerenciada do WordPress usam servidores separados para hospedar bancos de dados. Nesse caso, as informações do host do banco de dados não serão localhost.
Isso significa que você precisará entrar em contato com a empresa de hospedagem do WordPress para confirmar esses detalhes.
3. Reparar o banco de dados do WordPress
Agora você pode estar recebendo um erro diferente no painel wp-admin, como “Uma ou mais tabelas de banco de dados não estão disponíveis” ou “O banco de dados pode precisar ser reparado”. Nesse caso, você precisa reparar seu banco de dados.
Você pode fazer isso adicionando a seguinte linha no arquivo wp-config.php. Certifique-se de adicioná-la logo antes da linha “That’s all, stop editing! Happy blogging”:
define('WP_ALLOW_REPAIR', true);
Depois de fazer isso, você poderá ver as configurações visitando esta página: http://www.yoursite.com/wp-admin/maint/repair.php. Apenas certifique-se de substituir yoursite.com por seu próprio nome de domínio.
Aqui, você deve clicar no botão “Repair Database” (Reparar banco de dados) para iniciar o processo.
![Repair WordPress database Repair WordPress database](https://www.wpbeginner.com/wp-content/uploads/2020/01/repairwpdb-1.png)
Observação: o usuário não precisa estar conectado para acessar a página de reparo do banco de dados. Quando terminar de reparar e otimizar o banco de dados, remova essa linha de código do wp-config.php.
No entanto, se não quiser adicionar nenhum código ao site, você também poderá reparar o banco de dados no cPanel da sua conta de hospedagem.
Vá em frente e visite sua conta de hospedagem, onde você deve abrir a página “Websites” na coluna da esquerda. Em seguida, vá para a guia “Advanced” (Avançado) e clique no botão “Manage” (Gerenciar) na seção Database (Banco de dados).
![formidable-forms-field-label-min Click the Manage button next to the Database section](https://www.wpbeginner.com/wp-content/uploads/2020/01/click-manage-button-next-to-database-1.png)
Isso abrirá o cPanel em uma nova guia. Aqui, role para baixo até a seção “Modify Databases” (Modificar bancos de dados) e escolha o nome do seu banco de dados no menu suspenso “Repair Database” (Reparar banco de dados).
Depois de fazer isso, basta clicar no botão “Repair Database” (Reparar banco de dados) para iniciar o processo.
![formidable-forms-add-new-min Click the Repair database button](https://www.wpbeginner.com/wp-content/uploads/2020/01/click-repair-database-button-1.png)
O painel de hospedagem agora reparará automaticamente o banco de dados para você.
Quando o processo for concluído, você também verá uma mensagem de sucesso.
![formidable-forms-quiz-maker-install-min Database repair success message](https://www.wpbeginner.com/wp-content/uploads/2020/01/databasr-repair-success-message-1.png)
Agora você pode visitar seu site do WordPress para ver se o erro foi resolvido ou não.
4. Verificar se o servidor de banco de dados está inativo
Se tudo parecer estar correto e o WordPress ainda não conseguir se conectar ao banco de dados, o servidor do banco de dados(servidor MySQL) pode estar inativo.
Isso pode ocorrer devido ao tráfego intenso em um servidor. Seu servidor host simplesmente não consegue lidar com a carga (especialmente quando você está em uma hospedagem compartilhada).
Devido a isso, seu site ficará lento e poderá até mesmo gerar um erro para alguns usuários. Nesse caso, você deve entrar em contato com o provedor de hospedagem por telefone ou chat ao vivo e perguntar se o servidor MySQL é responsivo.
Além disso, se você tiver outros sites em execução no mesmo servidor, poderá verificar esses sites para confirmar se o servidor SQL está inativo.
Se você não tiver nenhum outro site na mesma conta de hospedagem, basta acessar o painel de controle de hospedagem e alternar para a guia “Avançado”.
Depois disso, clique no botão “Manage” (Gerenciar) ao lado da seção phpMyAdmin.
![formidable-forms-scored-quiz-min-new Click the Manage button next to the PHPMyAdmin option](https://www.wpbeginner.com/wp-content/uploads/2020/01/click-manage-button-next-to-the-phpmyadmin-option.png)
Isso abrirá o phpMyAdmin em uma nova janela, na qual você deverá clicar na opção “Database” (Banco de dados) na parte superior.
Depois disso, clique no nome do banco de dados para acessar suas configurações. Se conseguir fazer isso, então é hora de verificar se o usuário do banco de dados tem permissões suficientes.
![14 dicas vitais para proteger sua área de administração do WordPress (atualizado) Connect PHPMyAdmin with your database](https://www.wpbeginner.com/wp-content/uploads/2020/01/connect-phpmyadmin-with-database-1.jpg)
Para fazer isso, você precisa criar um novo arquivo chamado testconnection.php e colar o seguinte código nele:
<?php
$link = mysqli_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($link);
?>
Ao colar o código, certifique-se de substituir o nome de usuário e a senha pelos seus próprios. Agora você pode carregar esse arquivo no seu site e acessá-lo por meio de um navegador da Web.
Se o script for conectado com êxito, isso significa que o usuário tem permissões suficientes e que outra coisa está causando o erro.
Agora, você deve voltar ao seu arquivo wp-config e verificá-lo para garantir que todos os detalhes estejam corretos e sem erros de digitação.
Soluções adicionais que funcionaram para os usuários
Se as dicas de solução de problemas mencionadas acima não conseguirem corrigir o erro de conexão com o banco de dados em seu site, você poderá tentar estas etapas adicionais.
Conforme relatado por nossos usuários, essas etapas ajudaram alguns deles a resolver o erro de conexão com o banco de dados em seus sites.
1. Atualize o URL do site WordPress
Você pode tentar atualizar o URL do site do WordPress usando o phpMyAdmin no cPanel.
Basta acessar o phpMyAdmin no painel da sua conta de hospedagem e selecionar o banco de dados do WordPress na lista.
Depois disso, mude para o menu SQL na parte superior e digite a seguinte consulta MySQL:
UPDATE wp_options SET option_value='YOUR_SITE_URL' WHERE option_name='siteurl'
Ele deve ter a seguinte aparência:
![Como mostrar seus últimos pins do Pinterest nos widgets da barra lateral do WordPress Change site URL](https://www.wpbeginner.com/wp-content/uploads/2020/01/change-site-url-1.jpg)
Não se esqueça de fornecer o URL do seu próprio site e alterar wp_options
para o nome da sua própria tabela, pois você pode ter alterado o prefixo da tabela do WordPress.
2. Reinicialização do servidor da Web
Os usuários de servidores dedicados, servidores locais e servidores virtuais privados (VPS) podem tentar reiniciar seus servidores.
Isso reiniciará seu servidor da Web e de banco de dados, o que pode corrigir algumas falhas temporárias que estão causando o erro.
3. Pedir ajuda
Se tudo o mais falhar, talvez seja necessário entrar em contato com a empresa de hospedagem na Web. Todas as boas empresas de hospedagem WordPress o ajudarão a solucionar o problema, indicarão a direção certa ou até mesmo o resolverão para você.
Você também pode contratar desenvolvedores WordPress usando um serviço como o Seahawk para ajudá-lo a resolver esse problema por preços razoáveis. A melhor parte é que a Seahawk tem uma equipe dedicada de desenvolvedores especializados, portanto, você sabe que eles são confiáveis.
![Seahawk Media Seahawk Media](https://www.wpbeginner.com/wp-content/uploads/2021/02/seahawkmedia.jpg)
Além disso, você pode usar o serviço para manutenção do seu site, conversão de Figma para WordPress, reparo de sites invadidos, otimização de velocidade, reconstrução de sites, redação de conteúdo e muito mais.
Para obter detalhes, consulte nossa análise completa da Seahawk Media.
Esperamos que este artigo tenha ajudado a corrigir o problema “Erro ao estabelecer uma conexão com o banco de dados” no WordPress. Talvez você também queira consultar nosso guia de solução de problemas do WordPress para obter dicas sobre como resolver problemas do WordPress por conta própria ou nossas escolhas de especialistas das melhores ferramentas para freelancers e desenvolvedores do WordPress.
Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.
Syed Balkhi says
Hey WPBeginner readers,
Did you know you can win exciting prizes by commenting on WPBeginner?
Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
You can get more details about the contest from here.
Start sharing your thoughts below to stand a chance to win!
Arafat says
Sometimes when I click on the “Publish” button to post a new article on my WordPress blog, then this error message appears:
“”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 localhost. This could mean your host’s database server is down…..””
Despite the error message appears, my post got published and there is no problem with visiting my site. This error does not come after each post publication. Sometimes it occurs. (My hosting reseller provider changed my server some days ago and this problem began after coming to the new server) What is the problem and how to solve it, please tell …… Thanks.
Editorial Staff says
It sounds like that you are having a memory issue on the new server.
Administrador
Quinton says
The wp-config.php fix worked for me!! Thanks so much!
Josh says
I found a github repo which restarts the mysql server of wordpress if there is a database error using node.js http://goo.gl/gnXLR
Brian Deyo says
The quick snippet of PHP you provided was everything I needed to track down my issue.Thanks for the post!
Mario Ben says
I am very excited to find this solution. I got the exact problem with my website and after searching it, I found this amazing article.
Thank you so much!
HighHopes says
i was using Xampp on local machine to host my wordpress site and got error “Error Establishing the Database Connection”. first time i got that .. not sure why. i noticed in Xampp setup that the user and their privileges was deleted somehow. so i made a new user, using same user name as in ws-config, using host “localhost” and password same as in ws-config. worked like a charm![:)](https://www.wpbeginner.com/pt/wp-content/plugins/classic-smilies/img/icon_smile.gif)
Olly says
You’re a lifesaver. Many thanks!
Karl says
I got error but after couple minutes everything got back normal, any way to avoid getting this error in future?
ben says
really great post !![:)](https://www.wpbeginner.com/pt/wp-content/plugins/classic-smilies/img/icon_smile.gif)
helped me revive my wp-blog
thanks !
Demannu says
THANK YOU AUTHOR!!! Your little TestConnection script has saved me some serious non-paid time.
MUAH! / HUG / HIGH FIVE
El Hombre says
Really, this post has been a last-minute rescue. Many thanks to the editor.
Cheers el hombre
RaDLab says
Great article by the way.
My issue is somehow strange to me. In the last couple of days maybe weeks, every morning few of my sites on my server will get the Error establishing connection prompt. But after a few minutes, it starts to work without me doing anything. For example, I will get an email from a client that the Error is showing, but when I quickly check it on my end, it works fine, and The client will also notice it back up. So my problem is strange, I’m not sure what to check if everything seem to resolve itself. Is possible because of high traffic?
Editorial Staff says
Your issue is happening due to server overload. While this can mean high traffic, but it doesn’t always mean that. Sometimes, you have medium traffic but a bad plugin that is doing it. Other times, it is just high traffic.
Administrador
RaDLab says
Thanks for the response.
This has never happened before. Just today, I’ve had to restart MySQL several times to keep many of my sites running, while I try to figure why it keeps losing connection. I’m really baffled by this. I’ve looked into the php.ini looking for where to increase any sort of limits, but I come up with nothing. It’s running right now, but soon it will fail to connect until I restart MySQL.
Any ideas on how to adjust to the high traffic and keep the MySQL server running?
Editorial Staff says
One thing you can do is increase your PHP memory limit. If you are running at 32MB, then that could be a reason. But you will get to a point when your current servers just can’t handle it. You would have to upgrade. Not sure what your server specs are, and how much load you are putting on it.
Run your server logs and see which processes are causing the load. Then see if those can be eliminated or optimized.
XeNNo says
I have seen that too myself.
This is happening to me, not only with wordpress but also with joomla and piwik and everything that i use to work with and needs a database.
My provider seems to have a different machine for the MySQL service and every now and then the connection between my sites and the MySQL server drops and give me failure.
You should check that this is your case too… and if so… get another host service![:D](https://www.wpbeginner.com/pt/wp-content/plugins/classic-smilies/img/icon_biggrin.gif)
RaDLab says
Thanks for your input. I think I have narrowed it down to a db instance that was causing my MySQL to lose connection. It’s an instance running a ELGG system. Soon as I discovered how much load this instance was putting on the server, I deleted it. Since then, the Error has seem to have stopped. Who knew…
aly says
for me it was the sql password, which had a symbol ( ] ) at the end.![;)](https://www.wpbeginner.com/pt/wp-content/plugins/classic-smilies/img/icon_wink.gif)
After giving up on all other “fixes,” I edited the password and presto! All good
yogesh says
a very big thanks from me to you because first i website show 500 internel error i fix it by read wpbeginner article now my site show error establishing a database connection i fix it by read your article….thankssssss
mhisyam6 says
My problem solved from this error just by reinstall/update the wordpress in the dashboard.
Raul says
Which version of wordpress did you upgrade to? I was previously on 3.5.1 but read that the 3.5 version is bugged, so I downgraded to 3.4.2. It’s more stable now but I still see the error…
Matt says
This has been a question asked by many of our past clients and is such a pain to explain this. Pretty much, 100% of the time I end up having to go in and fix it myself.
Fanto Chandra says
I just do repairing the database via cpanel-mysql database and choosing repair database and turn out working and can open the site again now. Thanks for the clue from your explanation.
Christine says
my own hosting company couldn’t help me. thank you. the first option worked great.
Alex Patterson says
Just went through this issue – and the problem turned out to be that my mysql database was by default using the old 16 byte hashes for the passwords, rather than the 41 byte hashes that the more recent versions of php scripts that WordPress uses requires.
To see if this is the issue, you can look at your user table in mysql:
select user, host, password from mysql.user;
If the password column for your user is 16 characters rather than 41, that is your issue.
You will need to temporarily set the hashing to 41 digits and then re-encode your password:
set @@session.old_passwords = 0;
set password for ‘wordpress_user’@’localhost’=PASSWORD(‘password’);
Joshua says
Just wanted to say “thank you” – this just saved me a ton of time and trouble.
Emdad Shaon says
Thanx man……changing mysql password fix my problem…. RESPECT
Joe says
Where can I find the password for a mysql database?
Editorial Staff says
This is in your cPanel.
Administrador
Jamie says
What should I do if it won’t let me log into my cpanel either?![:(](https://www.wpbeginner.com/pt/wp-content/plugins/classic-smilies/img/icon_sad.gif)
Editorial Staff says
Contact your web hosting provider.
Administrador
TP says
Great tip I was able to login through backend and reload my site with no more error messages. Took five minutes! Thanks.
Geeky says
Thank you, changing password and username worked!
YF says
THANKS A LOT!!!!
This really helped me.
Markus says
After editing the wp-config.php and updating with new credentials, the error was still present. I had also to clear my APC opcode cache!
Evik says
Hi,
thank you for this article. I got this error twice and each time I tried to login into my cpanel it helped. Nothing else, but log into the cpanel resolved my problem.
It does not make sense, and I have no idea what is going on.
I got the message every time after I have made some changes on the website (the last time I was putting on a new email subscription).
Ben Nafi says
Thanks sharing..![:)](https://www.wpbeginner.com/pt/wp-content/plugins/classic-smilies/img/icon_smile.gif)
Thats helped me..
Rae says
Aside from updating wp-config.php, I had to update the domain for the following tables:
wp_blogs
wp_site
wp_options -> option_value (for option_name siteurl, home)
If you use WPMU, you will need to update ALL wp_options tables.
The error would NOT go away until all of this was done.
sara says
This happened to our site the other day, we got the dreaded error! We received a large amount of traffic but it was expected. We were using Quick Cache as the plugin and the hosts changed it for Super cache and also told us we had hit MySQL max_user_connections due to the queries on the wp_options table. They told us after installing super cache it’s taken us from 600+ database connections to under 5.
After installing the super cache plugin everything worked great again. Now I am concerned about this happening in future, what can I do to try and prevent this? We will always have a large surge in tarffic and then very quiet moments. How can I be sure the database will be able to cope with such demands?
Thanks
smithers says
i had “error connecting to database” problem twice in the past two days on a wordpress site on an amazon ec2 micro instance. it occurred after sending out a blast email regarding a fund raising campaign and asking people to check out the site, so i assume it was a load-related failure. anyway, the first time it occurred, i tried to restart the database (service mysqld restart), and it shutdown OK but wouldn’t restart. i then restarted apache (service httpd restart) and then restarted the database, and the database and site came back up.
the problem occurred again today, and the database restart worked without having to restart apache.
Editorial Staff says
Are you using a proper caching solution? This shouldn’t happen unless you are receiving a crazy load of traffic.
Administrador
Jon says
The scenario you describe is almost certainly caused by your EC2 instance being out of available memory. When you restart Apache a huge chunk of memory is released; only the minimum resources required to get the server up and running are re-allocated when Apache comes back up, then mysqld has plenty of elbow room to start.
A few good places to start fixing this:
1. Check your php.ini memory limit
2. Check your innodb_buffer_pool_size setting in my.cnf
3. Check your swap space
Jamie says
I’m running an Amazon EC2 instance also & restarting apache & then restarting mysqld worked for me too.
Daniel says
I was moving some webspace from an older to a newer server and tested some things, got stuck with this error. This helped, thanks a lot:
update wp_options set option_value=’http://www.newsitename.de’ where option_name=’siteurl’;
Shawn says
Thanks a lot! I was waiting for support from my host for hours…Sundays…but they took too long. My problem was my database password in wp-config, which was different from the real password. I changed it and everything is fine again.
*bookmarked
hanneng says
recently I also face the same problem on my blog at http://www.hanneng.net after moved to a VPS.
the solution is to modify the wp-config.php
define(‘DB_HOST’, ‘localhost:/tmp/mysql.sock’);
tristan says
Thank you so much! I had messed around in my functions php and lost the ability to open my website. in the process of trying to fix this issue I changed my password for database access and had no idea it was the cause for my error establishing database connection. I’m sure this seems fairly simple to someone who is familiar with this web stuff but for someone like me who is just a dabbler it was very frustrating. website works great now! thank you.
XeNNo says
Actually I’ve had a different problem and took me some time to resolve it. My wp after moving from one server to another, editing all files needed (wp-config) started loading on home page nicely. Also the wp-admin section worked like a charm … but still the problem apeared when I started to point on pages and articles … all of theme besides homepage get me the mysql error regarding connection to database….
everything started to work …
So…. looking on the internet I’ve found this article of yours and tried your advices … my problem not getting resolved on any of them.
Somehow … don’t know why… my .htaccess file pointed on another default root document and after editing my .htaccess ….
Thought somebody will need that …
Anne says
MANY many thanks for posting this. Thought I was going to have to start all over. Being one step above novice is not always sufficient! GAH!
Sean Murphy says
Thanks for this post. The adding that line of php code in the first para did the trick for my sites.
Lucy Gage says
Hi there,
I am getting this error every day “Error establishing a network connection”. The site was working perfectly, then after the first day I got up in the morning and check the site and saw the error for the first time. I logged into the crazy domains control panel and the database was missing. I called support and it took them all day to fix the problem, but then the site was ok again.
The next morning the same problem again. I called support again. After a couple of hours the site was back working again.
The next morning – the same problem again. another hour speaking to support, but they don’t actually tell me what the problem is.
I am so worried about this and jsut want the problem fixed. Do you think it could be anything I have done whilst setting up the website, or just a problem with the host?
Editorial Staff says
It could be a number of things. One of the plugins you are using is exhausting the database server. Another reason could be that your host is overselling the shared hosting plan you maybe on. This would result in database connection error.
https://www.wpbeginner.com/wordpress-hosting/ << See this page if you are looking to find a better web host.
Administrador
Hayley says
I actually read half of the 2nd paragraph and managed to fix my site… excellent – thanks.
Editorial Staff says
Glad you got it fixed![:)](https://www.wpbeginner.com/pt/wp-content/plugins/classic-smilies/img/icon_smile.gif)
Administrador
Jenn Hunter says
Thank you for writing this article. It helped me when having to reload my WP website from a previous back up.
Damian says
What happened with me is the php.config’s password didn’t match..downloading config.php and putting in the proper password fixed it!
Guest says
Hi, I run WordPress multisite and just went through an update. I have a blog that has a static front page and a separate page for blog entries. When I tried to open the blog page, I got the above message, Error Establishing a Database Connection.
Turned out I needed to click the yellow bar that appears when you do a major WordPress update, to Update Network which synchs everything database-wise on all sites in your Multisite install. Blog page is viewable now and everything’s working fine!
Rob Rawson says
My solution was to install DBVisualizer and what it showed me was that while the dbname was right it was in the wrong case. So changing the db name from wp to WP in my wp-config.php resolved this issue. No idea how this worked in the first place since this was up and running.
Anna Crowe says
This was a well written and thorough article. Thank you. Not everything applied to me, but I was able to troubleshoot and identify the problem using some of these suggestions. I’m praising your name today! Thanks.
Jacob Degeling says
Hi,
I moved my wp-config.php from the dir below the www root into the www root. That brought the site back up. I would prefer the wp-config.php to be outside the www root, so I’ll have to look into why it wasn’t working in the first place.
Thanks for the help.
Jacob
chris says
sql.safe_mode=On in php.ini hosed my multisite install this way. Change it back and the site came up again.
blkbam says
One thing to check on if you are moving from your system to the server and using MySQL is the case of the database name. In my situation the server is in all lowercase while my development is all uppercase. Iit’s a very easy over site.
Editorial Staff says
Good suggestion![:)](https://www.wpbeginner.com/pt/wp-content/plugins/classic-smilies/img/icon_smile.gif)
Administrador
Laura says
I had this error on my site – i called my host who told me that my username was being denied permission to the database.
No idea how this happened as I hadn’t gone near these details. However, they assured me this was a common problem.
Within 1 minute of the phone call ending, my site was back up and running.
Very strange….but glad its working again!
Great article btw! Glad i didnt need to use it in the end but very easy to understand if i had!
Editorial Staff says
Yeah sometimes the cats that work in the servers start having hiccups
Glad that your site is working now.
Administrador
RB says
My wordpress site was working fine. Then I got the “Error Establishing the Database Connection” message. Doing a Google search, there was a lot of information on what to do. This was the most helpful to me. It ended up that my database options table had crashed. I repaired it per this post and my wordpress site it works fine again. Thanks!
Asif says
try checking for the php version as well, sometimes it is the php version on the server that could cause the issue.