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

Come risolvere l’errore di stabilire una connessione al database in WordPress

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Viene visualizzato l’avviso “Errore nello stabilire una connessione al database” in WordPress?

Si tratta di un errore fatale che rende il sito inaccessibile agli utenti. Si verifica quando WordPress non è in grado di stabilire una connessione al database. Poiché diversi fattori possono influire su questa connessione, l’errore può essere un po’ difficile da risolvere per i principianti.

In questo articolo vi mostreremo come risolvere facilmente l'”Errore nello stabilire una connessione al database” sul vostro sito WordPress, passo dopo passo.

Fix the Error Establishing a Database Connection in WordPress

Cosa causa l’errore di stabilire una connessione al database in WordPress?

Un database è un software che facilita l’archiviazione, l’organizzazione e il recupero di dati da altri software.

Come sistema di gestione dei contenuti, WordPress utilizza un database per memorizzare tutti i contenuti e gli altri dati del sito web. Si connette quindi al database ogni volta che qualcuno visita il vostro sito web.

WordPress ha bisogno delle seguenti informazioni per connettersi al database:

  • Il nome del database
  • Nome utente e password del database
  • Server di database

Queste informazioni sono memorizzate nel file di configurazione di WordPress, chiamato wp-config.php.

Se una di queste informazioni non è corretta, WordPress non riuscirà a connettersi al server del database e verrà visualizzato l’errore “Errore nello stabilire una connessione al database”.

Database connection error in WordPress

È uno degli errori più comuni di WordPress. Oltre alle credenziali errate, questo errore può comparire anche se il server del database è inattivo o i file del database sono corrotti.

Detto questo, vediamo come risolvere il problema “Errore nello stabilire la connessione al database” in WordPress con una risoluzione dei problemi passo dopo passo.

1. Controllare le credenziali del database di WordPress

Il motivo più comune per cui si verifica un errore di connessione al database è la presenza di credenziali errate. Se avete recentemente spostato il vostro sito WordPress su un nuovo host, è probabile che il problema sia questo.

Le credenziali del database di WordPress sono memorizzate nel file wp-config.php. È il file di configurazione di WordPress che contiene importanti impostazioni, tra cui le informazioni sul database.

Se non avete mai modificato un file wp-config.php, date un’occhiata alla nostra guida per principianti su come modificare il file wp-config.php per maggiori istruzioni.

Si cercheranno le seguenti righe nel file 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' );

In questo caso, è necessario assicurarsi che le informazioni relative al nome del database, al nome utente, alla password e all’host del database siano corrette.

Potete confermare queste informazioni dalla dashboard del vostro account di hosting WordPress. Per questo tutorial utilizzeremo Bluehost, ma la procedura sarà simile anche per altri pannelli di hosting.

Una volta effettuato l’accesso, fare clic sulla scheda “Sito web” nella colonna di sinistra e poi passare alla scheda “Avanzate”. Quindi, scorrere fino alla sezione “Database” e fare clic sul pulsante “Gestisci” accanto ad essa.

Click the Manage button next to the Database section

In questo modo si aprirà la pagina dei database MySQL in cPanel in una nuova finestra.

Qui, nella sezione “Database corrente”, si trovano il nome del database e il nome utente. Ricordate di copiare e incollare questi dati in un blocco note per poterli aggiungere al file wp-config.

Find your database name and username in the Current Databases section

Quindi, scorrere fino alla sezione “Utenti attuali”, dove è possibile fare clic sul link “Cambia password” accanto al nome del database.

Si accede così a una nuova schermata, in cui è possibile modificare la password del database secondo le proprie esigenze.

Change your database password

Una volta confermati tutti i dettagli del database, è possibile modificare le informazioni nel file wp-config.php, se necessario.

Quindi, provare a visitare nuovamente il sito web per verificare se l’errore di connessione al database è scomparso.

Se l’errore è ancora presente, significa che c’è qualcos’altro che non va.

2. Controllare le informazioni sull’host del database

Se si è certi che il nome del database, il nome utente e la password siano corretti, occorre assicurarsi di utilizzare le informazioni corrette sull’host del database.

La maggior parte delle società di hosting WordPress utilizza localhost come host del database. Tuttavia, alcune società di hosting WordPress gestite utilizzano server separati per ospitare i database. In questo caso, le informazioni sull’host del database non saranno localhost.

Ciò significa che dovrete contattare la vostra società di hosting WordPress per confermare questi dettagli.

3. Riparazione del database di WordPress

Ora potreste ricevere un errore diverso nella dashboard di wp-admin, come “Una o più tabelle del database non sono disponibili” o “Potrebbe essere necessario riparare il database”. In questo caso, è necessario riparare il database.

È possibile farlo aggiungendo la seguente riga nel file wp-config.php. Assicuratevi di aggiungerla subito prima della riga “Questo è tutto, smettete di modificare! Buon blog”:

define('WP_ALLOW_REPAIR', true);

Una volta fatto ciò, è possibile vedere le impostazioni visitando questa pagina: http://www.yoursite.com/wp-admin/maint/repair.php. Assicuratevi di sostituire yoursite.com con il vostro nome di dominio.

A questo punto, è necessario fare clic sul pulsante “Ripara database” per avviare il processo.

Repair WordPress database

Nota: non è necessario che l’utente sia connesso per accedere alla pagina di riparazione del database. Una volta terminata la riparazione e l’ottimizzazione del database, assicurarsi di rimuovere questa riga di codice dal file wp-config.php.

Tuttavia, se non volete aggiungere alcun codice al vostro sito, potete anche riparare il database dal pannello di controllo del vostro account di hosting.

Visitate il vostro account di hosting e aprite la pagina “Siti web” dalla colonna di sinistra. Quindi, passate alla scheda “Avanzate” e fate clic sul pulsante “Gestisci” nella sezione Database.

Click the Manage button next to the Database section

Si aprirà cPanel in una nuova scheda. Qui, scorrere fino alla sezione “Modifica database” e scegliere il nome del database dal menu a discesa “Ripara database”.

Una volta fatto ciò, è sufficiente fare clic sul pulsante “Ripara database” per avviare il processo.

Click the Repair database button

Il pannello di hosting riparerà automaticamente il database.

Una volta completato il processo, verrà visualizzato un messaggio di successo.

Database repair success message

Ora potete visitare il vostro sito WordPress per vedere se l’errore è stato risolto o meno.

4. Controllare se il server di database è inattivo

Se tutto sembra essere corretto e WordPress non riesce ancora a connettersi al database, è possibile che il server del database(server MySQL) sia inattivo.

Questo potrebbe accadere a causa del traffico intenso su un server. Il vostro server host non è in grado di gestire il carico (soprattutto se avete un hosting condiviso).

Per questo motivo, il vostro sito diventerà lento e potrebbe anche dare errore ad alcuni utenti. In questo caso, dovreste telefonare o chattare con il vostro provider di hosting e chiedere se il vostro server MySQL è reattivo.

Inoltre, se avete altri siti web in esecuzione sullo stesso server, potete controllarli per verificare che il vostro server SQL sia inattivo.

Se non avete altri siti sullo stesso account di hosting, andate semplicemente nel vostro cruscotto di hosting e passate alla scheda “Avanzate”.

Successivamente, fare clic sul pulsante “Gestisci” accanto alla sezione phpMyAdmin.

Click the Manage button next to the PHPMyAdmin option

Si aprirà phpMyAdmin in una nuova finestra, dove si dovrà fare clic sull’opzione “Database” in alto.

Quindi, fare clic sul nome del database per accedere alle sue impostazioni. Se ci riuscite, è il momento di verificare se l’utente del database ha i permessi sufficienti.

Connect PHPMyAdmin with your database

Per farlo, occorre creare un nuovo file chiamato testconnection.php e incollarvi il seguente codice:

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

Dopo aver incollato il codice, assicuratevi di sostituire il nome utente e la password con i vostri. Ora è possibile caricare questo file sul proprio sito web e accedervi tramite un browser.

Se lo script si è collegato correttamente, significa che l’utente dispone di permessi sufficienti e che l’errore è causato da qualcos’altro.

Ora è necessario tornare al file wp-config e analizzarlo per assicurarsi che tutti i dettagli siano accurati e senza errori di battitura.

Altre soluzioni che hanno funzionato per gli utenti

Se i suggerimenti per la risoluzione dei problemi di cui sopra non riescono a risolvere l’errore di connessione al database sul vostro sito web, potete provare questi ulteriori passaggi.

Come riportato dai nostri utenti, questi passaggi hanno aiutato alcuni di loro a risolvere l’errore di connessione al database sui loro siti web.

1. Aggiornare l’URL del sito WordPress

Potete provare ad aggiornare l’URL del sito WordPress utilizzando phpMyAdmin in cPanel.

È sufficiente accedere a phpMyAdmin dalla dashboard dell’account di hosting e selezionare il database di WordPress dall’elenco.

Quindi passate al menu SQL in alto e inserite la seguente query MySQL:

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

L’aspetto dovrebbe essere il seguente:

Change site URL

Non dimenticate di fornire l’URL del vostro sito e di cambiare wp_options con il nome della vostra tabella, poiché potreste aver cambiato il prefisso della tabella di WordPress.

2. Riavvio del server Web

Gli utenti di server dedicati, server locali e server privati virtuali (VPS) possono provare a riavviare i loro server.

In questo modo si riavvia il server web e il database, che potrebbe risolvere alcuni problemi temporanei che causano l’errore.

3. Chiedere aiuto

Se tutto il resto non funziona, potrebbe essere necessario contattare la società di web hosting. Tutte le buone società di hosting WordPress vi aiuteranno a risolvere il problema, vi indicheranno la direzione giusta o addirittura lo risolveranno per voi.

Potete anche assumere sviluppatori di WordPress utilizzando un servizio come Seahawk per aiutarvi a risolvere questo problema a prezzi ragionevoli. La parte migliore è che Seahawk ha un team dedicato di sviluppatori esperti, quindi sapete che ci si può fidare.

Seahawk Media

Inoltre, potete utilizzare il servizio per la manutenzione del sito, la conversione da Figma a WordPress, la riparazione di siti violati, l’ottimizzazione della velocità, la ricostruzione di siti web, la scrittura di contenuti e molto altro ancora.

Per i dettagli, potete consultare la nostra recensione completa di Seahawk Media.

Speriamo che questo articolo vi abbia aiutato a risolvere il problema “Errore nello stabilire una connessione al database” in WordPress. Potreste anche voler consultare la nostra guida alla risoluzione dei problemi di WordPress per avere suggerimenti su come risolvere i problemi di WordPress da soli, oppure la nostra selezione di esperti dei migliori strumenti per freelance e sviluppatori di WordPress.

Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

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.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

663 commentiLascia una risposta

  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!

  2. Hajjalah says

    I used to get this error more often when I was logged into my admin dashboard for a longer period but this article helped me solve the issue. I just updated the WordPress Site URL. Thanks for the useful guide.

  3. Dennis Muthomi says

    I actually encountered this database connection error just recently when working on a staged WordPress site before going live.
    I had just moved a WordPress site from local to a vps. The video tutorial at timestamp 2:53; helped me solve the error :-)

  4. Jiří Vaněk says

    May I ask what the problem is, if I migrate the database to a new one, edit wp-config.php for the new connection, but wordpress does not connect? In the end, I had to delete the old wp-config and create new ones from the installation package. The only thing I found out was that the key stored in wp-config is probably a problem. Am I encrypting somehow connected to the DB and does it have to be removed from the wp-config file during the migration?

    • WPBeginner Support says

      You would want to ensure you have a user on that new database with the correct information that you have in your wp-config for the most common cause for that issue.

      Admin

    • WPBeginner Support says

      The steps in this guide should still be able to assist you and we would recommend reaching out to the support for the demo you are importing and they can look into what could be the root of the problem you are running into.

      Admin

  5. Henrik R. says

    I need to change the password for the MySQL database for security reasons.
    Isn’t there a way to login to the WP dashboard and tell WP about the new password, instead of having to change the wp-config.php file?

  6. LN says

    First I would like to say thanks for this guide!
    I am having an issue “Error establishing a database connection“ I have checked the wp-config.php and all the database information is correct. I wanted to try step 4 in this guide but I don’t really understand how. I logged in to phpMyAdmin, but not sure what the next step is. Do you have a video for that? I am not a developer just a new WP beginner.

    • WPBeginner Support says

      You would want to go to your hosting provider’s dashboard or reach out to your hosting provider and they should be able to assist.

      Admin

  7. Daniel says

    I almost have given up after having one issue after the other, till i read this. I had this feeling that “this is it” this is the solution I have been looking for. tried it and it worked perfectly, thanks a lot.

  8. Hrutik vijay kumthekar says

    I’m getting this error when entered the URL of my site:

    There has been a critical error on your website.

  9. jennifer mulder says

    I am getting this error
    Warning: mysqli_real_connect(): (HY000/2002): Connection refused in /home/f5853789/public_html/wp-includes/wp-db.php on line 1635
    Connection refused

    what do I do

    • WPBeginner Support says

      That is a different error, you would want to reach out to your hosting provider for assistance with that specific error.

      Admin

  10. Tejas Misra says

    I am a beginner to WordPress, and I am using MAMP to install WordPress but I’m still getting this error. My credentials are correct, and none of the steps shown above appeared to work. The database is repaired too. I don’t know what to do.

  11. sain says

    Hi, I have just moved my WordPress site to a new hosting provider via ftp when this error popped up. Is there anything I’m to update after a migration? Thanks

  12. KWS Adams says

    Adding this line “””define(‘WP_ALLOW_REPAIR’, true);”” helped me get my site back after 14 hours of being down. Thought it was my hosts problem. Thanks for the info.

  13. Zubair Rahman says

    How to increase the connection limit in the MySQL database? My website is intermittently giving database error as it is exceeding the max connection limit allocated on the server.

    • WPBeginner Support says

      You would need to reach out to your hosting provider for changing that and they would be able to assist.

      Admin

  14. Nimra afridi says

    I have installed a wordpress . i also make post but sometime it shows me that ”please install wordpress”. Why it showing me that?
    Thank you.

    • WPBeginner Support says

      There are a few possible reasons, you may want to reach out to your hosting provider to ensure there are no hiccups on their end.

      Admin

  15. alex says

    my website is hosted on aws and i accessed the MYSQL folder via filezila but i couldn’t find the file that contains database username , password and hostname. is there any specific name of that file?

  16. Deborah N. says

    Thanks. Adding the repair code to my wp config file worked. I appreciate the article. It was straight forward and easy to follow.

  17. bloggeryanke says

    your article was helpful i had changed my database password so it wasnt connecting to my blog properly but all thanks to your article the issue has been fixed

  18. Joe Marzi says

    Thank you for sharing such a nice blog.
    It will help the beginners of WordPress who are facing the problem regarding Error Establishing in the database connection. Apart from that, It gives a step by step solution so, every reader can easily solve the problem.

  19. Irwin says

    I got this error after forcefully shutting my computer. After trying all these suggested methods and failing, I rebooted my computer and the database error was fixed.
    You should give it a try too if things go south.

  20. Nick Aninsley says

    Thank you so much for sharing this tutorial. Actually, had installed WordPress, it shows me “Error Establishing A Database Connection” and I don’t know what to do. Then I have searched on Google and I found your this article and really it is
    very helpful for me and also many people who have no idea about this things. and my site were facing many other problems and only one of them has been solved. Thank for article.

  21. Emily says

    I can’t back up my site or do any of what you suggest, because I cannot get into the administrative section of my blog. I can view it, as a viewer, but I have no access to anything more. I also cannot find anyway to contact people from wordpress! Help!?!!

  22. Waqas Gulzar says

    Guys,

    I have fixed it now for my website

    It was due to insufficient PHP memory
    I have updated my php.ini to increase the PHP memory

  23. ken says

    I’m on BlueHost and just upgraded to WP 5.2 and got the dreaded error message:

    “Your PHP installation appears to be missing the MySQL extension which is required by WordPress.”

    I tried with PHP 5.6, 7.0 & 7.1 – all give the same response. Any ideas what I can try? My site is completely blocked by the error.

  24. ravendra says

    hello I need your help please help me my website is showing Error establishing a database connection
    how can I solve I don’t know please help me

  25. Daniel says

    I had this very same issue while using Xampp. After using the “testconection.php” file and through some further trouble shooting, I discovered that my user account was set to connect to “Any host” and by changing it to “Localhost” the problem was solved. I suspect this error came about when I updated Xampp and recreated the same named user.

    • Della says

      For my case the correct response was by Daniel.
      …I discovered that my user account was set to connect to “Any host” and by changing it to “Localhost” the problem was solved.

      Thanks so much!

    • WPBeginner Support says

      The methods in this article should be able to help with localhost sites as well as hosted sites.

      Admin

  26. Cosme Fulanito says

    After succeed the “Check your Web Host (MySQL Server)” test I change the host from 127.0.01 to localhost on the config.php file.

    That worked for me.

  27. Vinay Mourya says

    hi, it is happening to my WordPress site only sometimes and when I reload the page site starts working again please suggest me a solution, for now, I am using Cloudflare as cdn and wp rocket for caching plugin, the theme is newspaper premium.

    • WPBeginner Support says

      If it is intermittent like that, you would want to reach out to your hosting provider and let them know and they should be able to assist.

      Admin

  28. Gee says

    Same exact error i got “Error establishing a database connection” but not all of the sollution you mentíon helped me.

    For me the MySql services was disabled: I went to services and start the MySQL to automatic. The other thing was the ” log on ” to user was administrator and changed it to the account i created.

    Now my wordpress site is working again.

  29. Umar says

    I have a weird situation is, that the error establishing a database connection is only happening to one post in my blog while other posts are not showing this issue.

  30. rabda says

    I am receiving this error one time on 3 and not always! I do not understand why and how to solve the problem

    • WPBeginner Support says

      You may want to try reaching out to your hosting provider to see if their error logs have information that can help find the root of the issue.

      Admin

  31. Ryan says

    thanks so much, worked great, really appreciate how fast and to the point the video was, instead of a 7-10min extended one, boom, stright to the point!

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.