O aviso “Erro ao estabelecer uma conexão com o banco de dados” no WordPress é um erro fatal que torna seu site inacessível aos usuários. Isso acontece quando o WordPress não consegue se conectar ao banco de dados.
Como vários fatores podem afetar essa conexão, o erro pode ser um pouco difícil de solucionar para iniciantes.
Há 16 anos, administramos nosso blog no WordPress e encontramos vários erros e avisos, inclusive o “Erro ao estabelecer uma conexão com o banco de dados”. Com nossa experiência e muita tentativa e erro, aprendemos a solucionar esses problemas sem interromper nosso site.
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.
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).
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
Credenciais incorretas são a causa mais comum do erro de conexão com o banco de dados. 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.
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.
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.
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.
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 usando o 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).
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.
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.
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.
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.
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:
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 do WordPress usando uma plataforma como o WPBeginner Pro Services para ajudá-lo a corrigir esse problema por preços razoáveis. Temos uma equipe dedicada de desenvolvedores especializados em quem você pode confiar para resolver qualquer problema do WordPress.
Você também pode usar o serviço para manutenção de sites, reparo de sites invadidos, otimização de velocidade, reconstrução de sites e otimização de SEO.
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 nosso tutorial sobre como adicionar uma página de erro de banco de dados personalizada no 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.
Javatechig
Lovely. You saved my day.
CE
Thank you!!!!!!!! Worked like a charm!!
Mark Larson
You’re so helpful! All my writing was saved! Yes, I need to do a backup… I did one! Thanks so much, this is just the resource I needed. Luckily Google pulled it right up.
Michael Simoni
I have a test wordpress installation on my home computer running on fedora. I moved/reinstalled the computer with a recent copy of fedora. I restored the database and the wordpress installation. Everything should have been fine except I had the “cannot connect to the database” error. I have had this wordpress installation for a long time. Turns out that when I moved to the new server I also got a new my.cnf. Now I checked it and made everything the same but for some reason i did not add the following line in /etc/my.cnf. Maybe i just wanted to see what would happen. hmmm…what does this button do…..
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1
After I added that line, the database connection problem was fixed.
So I need to drop that user and recreate it with the new password format.
Note I also have
skip-networking
in /etc/my.cnf and….it works. That keeps mysql off the network, including 127.0.0.1. It’s just one less entry point for the mischief-makers.
Matt
I had a database-connection-error on a client’s site and could access the database via PHPMyAdmin but running the testconnect.php file suggested above came up with a response unlisted in this article:
“PHP Warning: mysql_connect(): No connection could be made because the target machine actively refused it.”
I got in touch with Fasthosts who my clients were with and it turned out that they had issues integrating PHP5.4 “and the only fix is to reset the MySQL database user password.”
So if you’re in that boat, then you may be able to fix it by accessing the database via PHPMyAdmin and running the query:
SET SESSION old_passwords = 0;
SET PASSWORD = PASSWORD(‘databasepasswordgoeshere’);
!! IMPORTANT NOTE !! : make sure you get ‘databasepasswordgoeshere’ correct otherwise you’ll be resetting your db password to something new rather than the same password and it could break your site even further!
Terry
I must be really dumb! i understand a little of wordpress but this all sounds way out of my leage.
I have tried to do exactly what you have said and this is what I get
Warning: Cannot modify header information – headers already sent by (output started at /customers/8/a/3/chigwelltkd.com/httpd.www/wordpress/wp-config.php:2) in /customers/8/a/3/chigwelltkd.com/httpd.www/wordpress/wp-includes/functions.php on line 2801
Error establishing a database connection.
I have no idea what to do next!!!
Not only have i lost the site from the web but I know cannot get in to wordpress admin.
IS THERE ANY HOPE!!!!!
WPBeginner Support
Undo the changes by accessing your site through FTP.
Administrador
Rowan Weismiller
Thanks so much for writing this post, it saved me quite a bit of time and a lot of headaches. Cheers!
SH
Solved my issue in less than 10mins cause of this article
YOUR ARE DOPE…you mean business
Thanks a mil!!!
alin
thanks man it’s worked!
Diana
thanks. very good article
Nayonika
This tutorial has really helped solving my problem!! Thanx a ton!
Lyndsay
Thanks a lot, this helped me fix my websites!
Sumi Ghosh
Hi,
Recently i uploaded a theme to the wordpress site, i have also uploaded the local database. I have modified my wp-config file too. Still i am getting error database connection error. When i opened my wp-admin it redirecting to wp-login.
Can i know what might be the problem?
WPBeginner Support
We think its normal behavior for wordpress to redirect you to wp-login.php when you try to access wp-admin directory. Can you please explain further? have you checked your wp-config.php file? does it have your live site’s database information?
Administrador
Aliesha
I had 4 sites give a 127.0.0.1 “Cannot connect to server” message & I also had no access to admin. I went through troubleshooting, & nothing helped. So, I contacted my web-hosting service, Bluehost, to inquire whether the MySQL server was responsive. The tech told me to login to my control panel’s File Manager, select “Show hidden files,” and then to go inside my root directory for each domain & rename my .htaccess file to .htaccess.old . He said he guessed that a plugin added code to my .htaccess file, causing my wp-admin to redirect to an IP address. It worked.
WPBeginner Support
Glad that it worked. However, you should find the plugin responsible for that and delete it.
Administrador
Erik de Vries
Just got this error on my own website. wp-config.php was allright. PhpMyAdmin could load the database. When trying to open the wp_options table PhpMyAdmin said the table must be repaired. Using the repair function in PhpMyAdmin fixed the table, reporting one row had been removed (not saying which one). No clue as to what caused this.
Thanks for the article, helped me debug the error.
Ben
Just got this problem, checked db through host cPanel and admin user seems to have been removed from database assuming that is why wp cannot connect. Problem is my ftp also seems to have been knocked out so i am unable to apply any solutions! sub-domain seems to still be working. It’s difficult to imagine this as being anything other than malicious!
WPBeginner Support
Contact your web host for support.
Administrador
Zimbrul
I just got this problem with one of my sites and fixing the database from wp-config.php did not work. I fixed it by upgrading to WordPress 3.6.1 in cPanel (Softaculous).
Kyra Dawson
Thank you guys! Great How To article!
Ike
Today, for some reason my site is facing the database connection issue.
• Confirmed my database access is working via testconnection.php.
• Changed the salt keys with new ones.
• Defined the proper site URLs to ‘WP_HOME’ and ‘WP_SITEURL’
• No issue with server slowness as my other websites in other root directories are working.
I’m guessing it may be a plugin recently added?
How do you properly uninstall a plugin if you can’t pull up both wordpress root and wp-admin directories in the browser?
Thanks in advanced.
Editorial Staff
Refer to this article:
https://www.wpbeginner.com/plugins/how-to-deactivate-all-plugins-when-not-able-to-access-wp-admin/
Administrador
Anudeep
Thanks a lot for such a good article!
My problem was a bit different. I had this issue because of ‘clicky analytics’ plugin.
I almost went mad as i didnt have any idea of what the problem could be. Finally after lot of trial and error i figured out that it was a plugin interference.
Giorgos
Thanks for the post
Is work to me
Naman Agrawal
Huh! sir you deserve an award.
It just worked for me. I was having this problem from last one month and you just served with this.
Thank you very much
Roeland Sanctorum
Problem occured when requesting new password and didn’t realise this was going to create a db problem. Fortunately I found your comments and guidelines. Problem solved in 3 minutes.
Thanks again (now I’ve subscribed to your weekly email)
Editorial Staff
Thanks Roeland Glad we were able to help.
Administrador
Tamela
My problem happened when I moved the site to a new hosting. I’d altered the config file to match my new database, username & password. But nothing worked.
Your tip about checking the WP-admin page did the trick. It told me something was wrong with the username. I went into c-panel and realized I hadn’t tied the user to the database. Two seconds later, all was good!
You potentially saved me hours of testing the wrong things! Thanks!
Editorial Staff
Glad we were able to help
Administrador
Stu Farrimond
I want to give you a big kiss.
VERY useful.
However, my issue seemed a little odd – and it might help someone else:
This morning our domain produced error:
Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 30720 bytes) in /home/gurumaga/public_html/wp-admin/includes/class-wp-list-table.php on line 384
I tried to increase PHP memory allocation.
Added to wp-settings (in root folder):
define(‘WP_MAX_MEMORY_LIMIT’, ‘256M’);
resulted in:
‘Error establishing a database connection’
Removed line and added lower limit:
define(‘WP_MEMORY_LIMIT’, ’64M’);
resulted in:
‘Error establishing a database connection’
Removed all changes in wp-settings.php now as original.
‘Error establishing a database connection’ persisted (for 5 – 10 mins)
Before reverting to the original error:
Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 30720 bytes) in /home/gurumaga/public_html/wp-admin/includes/class-wp-list-table.php on line 384
I increased the PHP memory limit to: define(‘WP_MEMORY_LIMIT’, ’64M’); again
Then ran the database repair as you advised.
Although no database errors were identified, the site is now back up and running.
Odd – I’m not sure if you or anyone else can make sense of it??
Jamila
THANK YOU.
Editorial Staff
You are welcome
Administrador
Donatus
Thank you so much, i have repair my own and is working perfectly. my site is back
Michael
Embarrassed… I tried everything in this blog and was double checking everything…
It never occurred to me that I’d typo’ed when entering the password.
Doh! So, here’s a +! for double checking the basics
Shaqinah
Hi, I made the mistake of changing the home url, initially it was http://shaneynayguns.com/wordpress and the site url was: http://shaneynayguns.com/wordpress too. I then changed the site url to http://shaneynayguns.com (thinking that that will make my site go live, as you can tell I’m an absolute idiot at this). Nothing happened, so genius here, changed the home url to shaneynayguns.com. That’s when things start to go awry: I couldn’t log in to wp-admin anymore and going to .com/wordpress redirects me to an error page. (shaneynayguns.com remain unchanged and directs to a landing page) I then went on to a forum and followed the exact instructions which were:
1. go to phpmyadmin
2. go to the correct database
3. browse wp_option
4. edit site url (I changed it to .com/wordpress)
Apparently based on everyone’s comments, it worked for all of them… except me! shaneynayguns.com/wordpress now redirects to a page with “error establishing a database connection”! It’s driving me mental! I was hoping if any of you could help me with this. As is obvious, I have not a clue when it comes to web jargon so I would really appreciate a simplified solution. Yes I’m an idiot, and I terribly need help! (F.Y.I: I host on godaddy)
Thanks in advance!
Editorial Staff
Open your wp-config.php file and add this:
1-click Use in WordPress
Administrador
Anderson Tagata
Hey, this worked for me. My wordpress website is on Godaddy and i was trying to put inside of subdirectory. now it works. Just after this, show up some database upgrade screen then everything is fine. also, i took out these defines above and still working. thanks.
Zac
Thanks heaps for your info guide, helped me fix my problem.
To let you know my resolve, I could not see a typo in the wp-config.php but decided to delete my Database and linked Username. I then created new ones and manually updated the new data into the wp-config and boom straight in. One thing to note is the database and username were originally the same name, so not sure if that was an issue as its a new site.
Seth
My website is down and I keep getting “Error establishing database connection” message.
I checked my WP-Config.php page and it looks fine on the inside, but when I preview it, the page says this
Warning: require_once(reddoorplayhouse.com/open/wp-settings.php) [function.require-once]: failed to open stream: No such file or directory in /hermes/waloraweb096/b619/moo.reddoor1/wp-config.php on line 95
Fatal error: require_once() [function.require]: Failed opening required ‘reddoorplayhouse.com/open/wp-settings.php’ (include_path=’.:/usr/local/lib/php-5.2.17/lib/php’) in /hermes/waloraweb096/b619/moo.reddoor1/wp-config.php on line 95
What does that mean. And what can I do? Thanks for your help.
Michael Tidwell
This is a frustrating problem that has been happening multiple times to a few of my sites over the past few weeks. I can fix it easily enough by replacing the Unique Keys and Salts in my wp-config.php file (grabbing new ones at: https://api.wordpress.org/secret-key/1.1/salt), but then days later I have to replace them again… so while I can fix the symptom, I’m still trying to determine why this keeps happening at http://brioagency.com
Editorial Staff
This can be caused by a plugin that you have if it is messing with your settings.
Administrador
manesh
Thanks a lot man, repairing the database fixed my issue!
Andrew Stark
Hi
Just thought I’d thank you for helping me fix a site.
Changing localhost to the database IP address fixed my issue.
Thanks
Andrew
Editorial Staff
Thanks for leaving a comment Andrew. Glad to help
Administrador
Madhurie Singh
I had made copies of the files and saved them on the server.
So when today the database connection error occured, I relaized, I had changed user, , pwd, database access but nothing worked.
So renamed the current wp-config.php as wp-configold.php
and copied the wp-config.php from the archive and pasted as wp-config.php.
Voila it works.
Michael Stelly
Forgot that the database is “local” to the application. I used the site URL by mistake. Switched DB_HOST to ‘localhost’ and all is golden.
Thanks for the blog! +1
Ben
You know sometimes you just find the perfect resource and it answers all your questions. I tip people for pouring me a cup of coffee. I wish it was super easy to just put a buck or two in the wpbeginner tip jar right now, but I guess a thanks will have to do.
Editorial Staff
Thanks Ben. Its always our pleasure to help. The best way to thank us is by spreading kind words about our site or by simply sharing this article on twitter, facebook, etc
Administrador
jAMIE
WP Beginner is just awesome & so is Syed! I don’t know how many times my search results have let me to your site and each time, I’ve learned something really helpful, useful, & practical.
This time, with my database connection error issue, I just had to clear my browser’s cache. FML Anyways, that was the advice that I got after contacting my host. It seems to have worked & hopefully that’s all it takes! How to prevent it from happening again is above me.
Mibo
All I have to say: “THANK YOU!” your post fixed my issues and spared me a couple of hours of work.
Fre
For me the issue was solved by properly setting “siteurl” and “home” in wp_options table did the trick for me, I could log into my admin and change everything!
One day I’ll buy you a cookie!!
Julie Anderson
I have a big problem… i did not set the site up and do not have axxess to the php or any files. i was trying to add pages and the next time i visited the site there was the error. Do i need to get to the admin initiator etc, is there no other way into the site?
Editorial Staff
You need to have admin access to the site.
Administrador
umar satti
You are My HERO
Stephen Doxsee
I get this error intermittently. Perhaps I don’t have enough resources on my amazon ec2 free tier instance. I’ve had the problem 3 times in the last week but have been able to solve it each time by restarting the database server.
Thanks for the post
udumbuke
For me issue was solved by properly setting “siteurl” and “home” in wp_options table
Mana
Thank you so much, Udumbuke. This was exactly the step I forgot in moving my site to a new host. I’m so glad I can stop headaching over this! And great guide altogether on this site.
Joyce Keller
This error happened to me because I wanted to back up my database and could not remember the password. I changed the password in GoDaddy – but this didn’t change it in the wp-config.php! Once I changed it in wp-config, everything worked okay again.
THANK YOU FOR SUCH A COMPREHENSIVE SOLUTION!!! And a truly useful site. Kudos!
JD
In step review of wp-config.php you have to consider the user name and password that is there in the file, the user may not exist in the database (mysql), the password has changed so check if there is the user. In case the user does not exist in the database create it, assign the password found in wp-config.php and provide permits for administration of the database (DBA).
This happened to me to restore my wordpress.
Oliver Wieland
Thanks dude! Restored my database and all i needed to do then was reassign the correct user with the correct database in cpanel.
Pat Walsh
Hi guys, thanks for this info.
Helped me to fix a problem with a WordPress site I created.
It had been happily running for over a month when it started having the “Error Establishing a Database Connection” error.
Finally fixed it by changing DB_HOST to use the full host name rather than the ‘localhost’ that had been in there before.
I don’t know why it worked initially and then stopped working. But its working now…
Cheers,
Pat Walsh
Forma
Having the same connection to DB problem, and after reading comments, I decided to change the wp.config file refrence to my actual host to localhost and for some reason that fixed it. So my solution was the opposite to the one above. Just a shot in the dark…
arman
it is indeed helpful for me as i m facing this problem currently… thanks for this great article..
Arifur Rahman
I’m getting this issue temporary at my site just for few seconds.
how can I be free from this?
Please help!
Editorial Staff
Find the root cause. It can be caused by a plugin. Or simply you need to upgrade your hosting plan if you are getting tons of traffic.
Administrador
Arifur Rahman
Thank you,
I already upgrade my hosting plan from basic to Pro.
But still same as before.
I using Adminimize, AG Custom Admin, Akismet, BuddyPress Template Pack, Display widgets, Fast Secure Contact Form, Google XML Sitemaps, Jetpack by WordPress.com, Page Views Count, Polldaddy Polls & Ratings, User Switching, Better WP Security, BuddyPress, Hotfix, W3 Total Cache, wordPress Importer and WordPress SEO.
Which one is making problem??
Have you any Idea?
Eduardo Capanema
If you have all the info in the config file correct and is still having the problem, check to see if you have any spam prevention plugin active such as Fail2Ban. I found that it was causing the database problem. I believe it happens cause when you’re editing the wordpress via wp-admin, you make too many sequence requests to the apache it triggers the Fail2Ban service for www-data user. Try uninstalling Fail2Ban or any other spam controller. Then, restart both mysql server and apache to get hid of the Error message.
I hope this helps.
b
Stefano
Thank you guys. Problem solved. Very good post