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

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.

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

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.

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

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

WPBeginner Pro Services

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.

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

660 ComentáriosDeixe uma resposta

  1. Abul Fayes

    Either ‘127.0.0.1:8889’ or ‘localhost:8889’ works for me. Just using ‘localhost’ with no port specified does not work. I am using MAMP

  2. Joe

    The frontend of my site is connecting but the wp-admin section is showing the error establishing a database connection.

    What do I do?

  3. Gill

    Thanks! Life saver. Completely borked my site changing passwords. Could have sworn I’d done everything right but managed to fix it in config.

  4. Praveen

    My problem was due to a google analytics plugin, the day i installed it, my site was down saying “Error database connection!” Even I was unable to login into my admin panel. So, I manually removed that plugin from cpanel, and everything worked.

    • Andreja

      Hi Praveen,

      thank you for your info. Can you please explain how to find particular plugin in cpanel to remove it? I received this error message right after I’ve installed “All in one SEO pack” plug-in in my Worpress site so I guess it could be the same problem as your problem was…?

      Thank you in advance!

  5. Matt

    I was on a Digital Ocean 512MB droplet and was getting this error every couple of weeks. Inspecting the logs showed that a process called update-apt-xapi was consuming all of my memory and causing the mysql service to crash resulting in the error. You can try setting up a swap file but, really, 512MB just isn’t enough memory to run a Wordpress install. Upgrade your droplet to 1GB and that should take care of the issue.

    • Joween Flores

      We have the same issue here friend. How’s your website going since? I was trying to cheap on server expenses now.

  6. Ob

    I just checked MySQL server with “service mysql status”. Apparently, MySQL server was not running.
    So, I started it with: “service mysql start”. And Voila! my website was up.

  7. Kishan SHarma

    What i found is it was faulty plugin which was causing trouble , try deactivate plugins and check if problem persist. changing localhost to 127.0.0.1 also solved some issues

  8. Jim Zimmer

    I did a search through your post and didn’t find anything about SELinux being the culprit, which ultimately was my problem. I have segregated my web server from my database and disabled SELinux on both VMs. I tried your testconnection.php, which was successful from within the /var/www/html directory before disabling SELinux, so I really have no idea if it is the database or the web server that has the issue. I will try and update this comment with SELinux settings that work when I have tested it.

  9. Andrea

    I have this problem right after having changed the password for my admin access. Can you super kindly provide a solution written in a language understandable for someone who has close to 0 programming or web-developer knowledge?? I have the error for both front-end and back-end. I have NO IDEA how to “check the wp-config.php” file (never heard of it until now). How do I proceed?

    Thank you so much,
    Best,
    Andrea

  10. Binyam

    What did work for me was this: In cPanel, go to Advanced Zone Editor select the domain copy the recorded IP and as wpbeginner suggested I replacing localhost with the IP and it works! Thanks!

  11. Avinash

    I was having the connection problem. The problem was my previously installed MySQL, was running. So I stopped it and then ran MySQL of Xampp. It worked. Hope it helps.

  12. Avinash

    My previously installed mySQL was running. I stopped it and then ran mySQL that came with Xampp. it worked. Hope it helps.

  13. Swati

    We had our wordpress installed on AWS EC2 and we got the “Error establishing database connection” for all our sites when the database was installed on the same server as the web server. When the database was moved to Amazon RDS for each of our sites, that error did not recur.

  14. Luis Daniel

    Hi!
    This helped me a lot with a WP installation going bad. Thanks!

  15. Scott

    Greetings.

    I have recently experienced the same issue when moving my multi-site from a subdirectory to root. Even after going through all the steps outlined in various tutorials, I encountered this dreaded message and nothing I did seemed to work.

    What did work for me was this: In cPanel, go to your softaculous script installer, select the edit icon for your WordPress installation, change the paths that point to your install.

    Once I did this and saved, then navigated to my site URL, it was back up and running smoothly.

    Just wanted to leave this here in case it helps someone else along the way.

  16. John Henry Gaspay

    Thanks man, it work on ngnix server due to error establishing.

  17. Sysy

    I have an issue with database connection. I wanted to create a new database for a new website #2 connected in multisite in OVH, and when wordpress asked me to enter login, password etc I entered those of website #1 as I had to do BUT without changing “wp_” for “wp_2″… And now both of these two sites have the message “Error establishing a database connection”. I deleted all FTP WP for website #2 and deconnected from multisite, but impossible to get back and to enter in website #1!! Do you know how to resolve this problem?

  18. Taurai

    I’m having an issue with my website, my WordPress database just seams to disappear. logged into MySQL and nothing exist there anymore. has anyone ever experienced this? anyone with a solution?

  19. Gail Gardner

    The cause of this issue when I had it was so many people running hacking programs against my login page that they were impacting the server. It happened every Friday evening through Sunday evening.

    We eliminated the issue by protecting that page with a pop-up so they couldn’t run their automated hacking programs against the login page.

  20. Rita

    Thank you for posting this–it saved a bit of a panic when the company’s WP blog disappeared behind this error. After verifying that the database was still there and undamaged, I called our host.

    Turns out they’ve been migrating customers’ web sites to new and improved servers, and they somehow lost the connection info. Hopefully it will be repaired today.

    But a very informative article, and a quick reminder (for me) of how to check in on mySQL to make sure everything is still good. Thanks!

  21. adams

    i cant create pages, new post, or edit my themes or even upload pictures i constantly get the following error…

    This page isn’t working.
    didn’t send any data.
    ERR_EMPTY_RESPONSE
    the website setup is new but am faced with this problem

  22. Wayne

    Thanks. Helped me debug a DB backend issue.

  23. jitesh

    How can i find my wordpress database username and password?

    By Mistake, i have deleted wp-config.php file and now i have uploaded new files.

    I am Using Godaddy’s windows server…

    I am getting below error:

    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 . This could mean your host’s database server is down.

    Are you sure you have the correct username and password? Are you sure that you have typed the correct hostname? Are you sure that the database server is running? If you’re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress Support Forums.

    Please help me as I have wasted by complete week…

    Thank you..

    • WPBeginner Support

      Hey Jitesh,

      You can login to your hosting control panel and locate the MySQL database section. Most likely, you will be able to find the database name, username, and password information there. Alternately, you can contact support to help you locate that information.

      Administrador

  24. Bob

    Thanks so much, all, for maintaining such a great website! You guys continue to bail me out with problems, issues & fixes for those of us who just enjoy writing & posting and not dealing with all of the WordPress programming stuff. Great work!
    Cheers!!!!

  25. Joette

    Thanks for all the great articles. I am having such a problem tho just getting WP installed. I’ve followed your instructions regarding doing it with MAMP and keep getting the “can’t connect to localhost:8888” msg. After much searching I found a terminal code to test apache. It returned with httpd not running, trying to start. I did it again and it didn’t return anything so perhaps worked.

    I tried connecting to local host again and this time I got Error connecting to database. At least this seems like progress! I tried some of your suggestions above and this time, it seemed to be trying to connect for quite a while, but finally gave me the Error connecting to database again.

    I have yet to get the happy WP page. Does anyone at all have any ideas as to what is going on? I have spent hours searching, contacting, trying this and that and I don’t know what else to do at this point. I am an absolute WP beginner.

    Thanks to anyone/everyone in advance.

    • Ashley Knox

      Hey! Were you able to figure it out? I’ve tried all of their solutions and I’m still stomped.

      • Joette

        Hi Ashley, No, unfortunately nothing is working for me either! I’ve yet to find someone who knows the answer & have been asking many places. For me, I think I’m going to use different software and leave WP for another time. Too strange, too much hassle.

        • Kalico

          This isn’t a WordPress problem, it’s a MAMP problem. If you have to run this on a local server, try a different XAMP package. Better yet, get a shared hosting account and set it up there. Local XAMP can be frustrating.

  26. J M Landers

    I missed that when you add the repair line to your WP config file you have to add it right at the end of the declarations before the first “if” statement when I first read it. Took me a while to realize what I was doing wrong. Still didn’t fix my problem but at least I was able to strike one possible issue off my list.

  27. Muhammad Qamar40391

    Thank you for a great helpful post.
    Solved by resetting DB password but this process repeated several times. issue solved but page speed is too much slow now.

  28. John Malto

    Also had the same problem and tried everything. TestConnection was failing. What I just had to do was manually edit the user password through MySQL Cpanel and it suddenly worked!

  29. Leslie limardo

    I am so confused. First time on wordpress. No tech experience whatsoever. I didn’t receive any error. message. My website is up. The problem I had is when I set the page to update some updates would take effect and others didn’t. I called Wordpress and they told me I didn’t set up the database correctly. Is this the same issue as this article or something totally different? Thanks in advance.

  30. Fran

    Hi, i had this problem when I formatted my laptop and reinstalled XAMPP.

    Problem was, I forgot to create a new Mysql user with the same data (host, name and password) from my BD user stored on wp-config.php, just like we do when we configure one new WP site for the first time. That solved it :)

    So, maybe the problem is not that the user has not enough permissions… perhaps the problem is, user simply doesn´t exist yn mysql.user table! (as I said, it can be possible after formatting your computer).

  31. Ahmed

    thank you for the great help, i got mine up by replacing localhost with 127.0.0.1

  32. Kate

    I just had the same problem, which I managed to solve by simply changing the DB password and correcting that in the config.php file.

    I have no idea why the password suddenly became an issue, though.

  33. Sheriph

    Changing the localhost in my wp-config.php to the ip on my host account in godaddy cpanel did the magic for me. Even godaddy support were talking rubbish. Imagine telling to upgrade with about $200, that my hosting plan is low on resources. I almost believed until I found this article. Thanks a lot.

    • Steve

      I still have the problem. GoDaddy tried but unable to help. They have a service that, for $80.00, will have a WordPress expert investigate. However, there are no guarantees she / he can fix the problem but you still have to pay the $80.00.

  34. Destiny Alabi

    This review was very helpful,

    I had a similar issue with installation on windows server, I kept getting database error, and what I did was to replace localhost which was internal server to IP Address and Port which was external server and it worked perfectly.

  35. Sam

    Mine just happened like 20 minutes ago, I am hosting at Ipage and WHAT A SCARE!!! It happened all over sudden and I could not access both the admin site and the website itself with my laptop but I could access the site with my phone.
    Then before I could complete reading this guide the site got back by itself lol. I want to know if there is a way to avoid this from happening in future.

    • Robin Robin

      The same happened with my site. Very strange!

  36. Aaditya Koesis Sharma

    Nice article. I want to know about the AMP errors and how to fix them ?

    • Bongani Ngcobo

      This was helpful, Thank you very much. I always rely on WP Beginner when struggling.

  37. sreekan th reddy

    my website is showing database connection error .

    can some one help me to solve the problem

    my website is created in amazonweb service

    for every 24 hours it showing database connection error
    the php-myadmin ,wp-content every thing is fine
    can plz some one help to solve this issue

  38. Martin L.

    I have no WordPress account, but have been having this happen to me a lot recently on several sites. How can I fix this? (Note: I don’t own these other sites and I don’t think I can access their databases directly)

  39. imparthi

    Thanks much for the article. I ran into the same issue.
    1. Wp-Config file was correct
    2. phpMyadmin connection was success
    3. testconnection.php approach too was success
    4. I tried to update the site URL I couldn’t get it as naming conventions of the table names of the WP changed

    THIS IS WHAT HELPED ME FINALLY.
    I selected wp_Options” table in the phpMyAdmin window to browse the content, there was an informative Error message that, the table has to be repaired. (wp-config auto-repair didn’t work out)

    I was able to repair using the options available in phpMyAdmin and got my site back. :) Thanks all.

  40. jhaejhae jhaens

    hi there.. can i please seek help.. i am working now on transferring my live WordPress site to local using XAMPP.. my database is doing good but i cant connect it during the WordPress installation. please help.. thanks in advance!

  41. Tanya

    Hi there,

    Thank you for this article. My website was hacked recently and after I got no support from the hosting provider, I was told I was going to need to reinstall Wordpress and upload the backup. I didn’t use a backup plugins (I am all the way in South Africa) as it is to expensive for the paid plugins. So I did a cpanel backup through Softaculous and downloaded the Zip of 1.03Gig. Two weeks later my site was hacked (Twice in one week). With the second hack my wordpress installation was comprimised – and backup deleted from server. So I had to delete the original installation and reinstall. Now I followed all the steps to upload the zip to file manager and now I am stuck with this: Error Establishing a Database Connection. I have tried all the suggested solutions from this post, but still no progress. Please help me! I am quite new to wordpress and this is my biggest client’s website.
    Kind regards,
    Tanya

    • WPBeginner Support

      Hi Tanya,

      The most common reason for this error is incorrect Database information in your wp-config.php file. Confirm that you have restored your WordPress database correctly, then enter the mysql host, database name, database username and password carefully. If you are unsure, ask your hosting provider and they will let you know your mysql host and other information.

      Hope this helps

      Administrador

  42. Mannu

    Some folks suggested that they fixed their problem by replacing localhost with the IP.

    It worked for me….
    Any logical explanation for this…?

    • Nick

      Think about it. ‘Localhost’ is the name of a location. If changing that to the IP works, then ‘localhost’ was not pointing where you need it to be.

  43. Andrew

    Thank you for your article, it was very informative and helpful in getting my issue resolved.

  44. Ravi

    I have MAMP installation on my Macbook. i.e I am running MySQL also on my local machine. My problem was that in wp-config.php, the database server ‘localhost’ is not working. Once I changed it to 127.0.0.1, it started working.

  45. Amanda

    What does it mean if testconnection.php is just a blank white page?

  46. Mike Crisp

    Repair database command worked for me.
    Front end or site was fine but couldn’t access admin panel – Repair found a damaged database file (wp-options) – repair worked

  47. JP Hoey

    What i did was, in the cPalen i went into MySQL databases and scrolled down to current user and changed the password. I used the very same password that was in my wp-config.php file but for some reason the password was corrupt. Everything works fine now.

    • Chuck Moran

      I got this error on a client’s site. After a bum steer chatting with a Bluehost tech, I called back and the phone tech support person I got did this same @JP Hoey trick (changing the DB pass and updating it in wp-config.php). Took 5 minutes and worked like a charm.

  48. Adam Coalbow

    An obscure one for me…

    Don’t use #’s in your password.

    I had two hash tags in my password that was throwing something off in the PHP–since hash tags create comments I guess. I removed the hash tags and BOOM, I’m in.

  49. Ted Richards

    First thank you for a well-documented article on “We were able to connect to the database server (which means your username and password is okay) but not able to select the XXXXXX database.”

    I tried almost everything outlined in the article but can’t fix my problem. Here is an outline and history.

    Local machine installation:
    I have installed MySQL 5.7.17 and MySQL WorkBench 6.3.8. And WordPress 4.7.2. The MySQL was installed after removing both an earlier version of MySQL and WorkBench. The previous version was displaying the same database error. The previous WordPress/MySQL worked about 2 years ago, but recently I contracted a project to develop a WordPress Web site, and I encountered this problem when I began setting up the new WordPress framework for this new site. The old WordPress site was deleted so I couldn’t test if that worked.

    So, I reasoned, why not try a fresh start and also upgrade to the latest versions, etc.

    But, this new version also had the same problem with not being able to connect to the database. I have narrowed down the problem to “permissions” and I haven’t been able to crack the code.

    The MySQL Server logs verify this is this case:
    Timestamp, Thread, Type, Details
    2017-01-28T02:46:24, 134, Note, Access denied for user ‘root’@’localhost’ (using password: YES)

    I have created a new WP directory and installed a fresh WP version etc.
    I deleted and created new databases in WorkBench and properly assigned them users and passwords.

    I have checked the Users and Privileges, Client Connections and can find nothing that would block access to the database.

    I have checked my Windows 7 permissions for the MySQL Directory and the sub directories. I have unchecked the “Read Only” to the master MySQL Directory and all directories and files are read/write.

    I have progressed through each attempt to connect to the database each time I change something.

    I am exhausted and very disappointed there isn’t a good response by the WP Support Team to this issue of “not able to select the database.” It is a “popular” issue that many developers are experiencing with no resolution–many more experienced than me, are having.

    You are my last hope!

    Thank you!

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.