Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Como corrigir o erro ao estabelecer uma conexão com o banco de dados no WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

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.

Fix the Error Establishing a Database Connection in WordPress

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).

Database connection error in WordPress

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.

Click the Manage button next to the Database section

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.

Find your database name and username in the Current Databases section

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.

Change your database password

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

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).

Click the Manage button next to the Database section

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.

Click the Repair database button

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.

Database repair success message

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.

Click the Manage button next to the PHPMyAdmin option

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.

Connect PHPMyAdmin with your database

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:

Change site URL

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

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.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

661 ComentáriosDeixe uma resposta

  1. 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!

    • Mark Larson says

      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.

  2. Michael Simoni says

    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.

  3. Matt says

    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!

  4. Terry says

    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!!!!!

  5. Sumi Ghosh says

    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 says

      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

  6. Aliesha says

    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. :)

  7. Erik de Vries says

    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.

  8. Ben says

    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!

  9. Zimbrul says

    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).

  10. Ike says

    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.

  11. Anudeep says

    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.

  12. Naman Agrawal says

    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 :)

  13. Roeland Sanctorum says

    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)

  14. Tamela says

    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!

  15. Stu Farrimond says

    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??

  16. Michael says

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

  17. Shaqinah says

    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!

      • Anderson Tagata says

        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.

  18. Zac says

    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.

  19. Seth says

    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.

  20. Michael Tidwell says

    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

  21. Andrew Stark says

    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

  22. Madhurie Singh says

    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.

  23. Michael Stelly says

    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

  24. Ben says

    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 says

      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

  25. jAMIE says

    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.

  26. Fre says

    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!!

  27. Julie Anderson says

    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?

  28. Stephen Doxsee says

    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

    • Mana says

      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.

  29. Joyce Keller says

    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!

  30. JD says

    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 says

      Thanks dude! Restored my database and all i needed to do then was reassign the correct user with the correct database in cpanel.

  31. Pat Walsh says

    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 says

      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…

  32. Arifur Rahman says

    I’m getting this issue temporary at my site just for few seconds.
    how can I be free from this?
    Please help!

      • Arifur Rahman says

        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?

  33. Eduardo Capanema says

    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

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.