Database Connection Error WordPress: Diagnosi e Riparazione

L’errore “Error establishing a database connection” indica un problema nel Database Handshake tra WordPress e MySQL. Può essere causato da credenziali errate, server MySQL down, o tabelle corrotte.

Diagnosi Rapida

Prima di tutto, identifica se il problema è:

  1. Credenziali errate in wp-config.php
  2. Server MySQL non raggiungibile
  3. Tabelle corrotte nel database
  4. Limite connessioni esaurito

Step 1: Verificare le Credenziali

Controlla i valori in wp-config.php:

# Via WP-CLI (se funziona)
wp config get DB_NAME
wp config get DB_USER
wp config get DB_PASSWORD
wp config get DB_HOST

# Oppure manualmente
grep -E "DB_NAME|DB_USER|DB_PASSWORD|DB_HOST" wp-config.php

Valori comuni per DB_HOST:

  • localhost – Server locale
  • 127.0.0.1 – Alternativa a localhost
  • localhost:/tmp/mysql.sock – Con socket
  • mysql.hostname.com – Server remoto

Test Connessione Manuale

# Test connessione MySQL
mysql -u YOUR_DB_USER -p -h YOUR_DB_HOST YOUR_DB_NAME -e "SELECT 1"

# Se funziona, vedrai:
# +---+
# | 1 |
# +---+
# | 1 |
# +---+

# Se fallisce con "Access denied": password errata
# Se fallisce con "Can't connect": server MySQL down

Step 2: Verificare lo Stato MySQL

# Controlla se MySQL è attivo
sudo systemctl status mysql
# oppure
sudo service mysql status

# Riavvia MySQL se necessario
sudo systemctl restart mysql

# Controlla i log MySQL per errori
sudo tail -50 /var/log/mysql/error.log

Su hosting condiviso? Contatta il supporto per verificare lo stato del server MySQL.


Step 3: Riparazione Tabelle Corrotte

Se la connessione funziona ma WordPress mostra ancora l’errore, le tabelle potrebbero essere corrotte:

# Test stato tabelle
wp db check

# Output se corrotto:
# wp_options: Table is marked as crashed
# wp_postmeta: 1 client is using or hasn't closed the table properly

# Ripara tutte le tabelle
wp db repair

# Output:
# wp_options OK
# wp_postmeta Repair status: OK

Metodo Alternativo via wp-config.php

// Aggiungi in wp-config.php
define( 'wp_ALLOW_REPAIR', true );

// Poi visita:
// https://tuosito.com/wp-admin/maint/repair.php

// IMPORTANTE: Rimuovi la riga dopo la riparazione!

Step 4: Ottimizzazione Database

Un database gonfio può causare timeout e problemi di connessione:

# Ottimizza tutte le tabelle
wp db optimize

# Controlla dimensione database
wp db size --tables

# Output esempio:
# +---------------------+-------+
# | Name                | Size  |
# +---------------------+-------+
# | wp_options          | 5 MB  |   <-- Spesso gonfia
# | wp_postmeta         | 12 MB |   <-- Può avere orfani
# | wp_posts            | 8 MB  |
# +---------------------+-------+

Pulizia wp_options (Autoload)

La tabella wp_options con troppe righe autoload rallenta tutto:

# Conta righe autoload (dovrebbero essere < 500)
wp db query "SELECT COUNT(*) as count FROM wp_options WHERE autoload = 'yes'"

# Trova le options autoload più pesanti
wp db query "SELECT option_name, LENGTH(option_value) as size 
FROM wp_options 
WHERE autoload='yes' 
ORDER BY size DESC 
LIMIT 20"

# Elimina transients scaduti
wp transient delete --expired

# Elimina TUTTI i transients (aggressive)
wp transient delete --all

Pulizia wp_postmeta Orfani

# Conta postmeta orfani
wp db query "SELECT COUNT(*) FROM wp_postmeta WHERE post_id NOT IN (SELECT ID FROM wp_posts)"

# Elimina postmeta orfani (FAI BACKUP PRIMA!)
wp db query "DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT ID FROM wp_posts)"

Pulizia Revisioni

# Conta revisioni
wp post list --post_type=revision --format=count

# Elimina TUTTE le revisioni
wp post delete $(wp post list --post_type=revision --format=ids) --force

# Limita revisioni future in wp-config.php
define( 'wp_POST_REVISIONS', 5 );

Step 5: Backup e Recovery

# Export database completo (SEMPRE prima di modifiche)
wp db export backup-$(date +%Y%m%d-%H%M).sql --add-drop-table

# Export solo struttura (per debug)
wp db export structure.sql --no-data

# Import da backup
wp db import backup-20260215.sql

# Ricerca e sostituzione URL (dopo migrazione)
wp search-replace 'https://old-domain.com' 'https://new-domain.com' --all-tables

Errori Specifici e Soluzioni

“Too many connections”

# Il server ha raggiunto il limite di connessioni
# Soluzioni:
# 1. Attendi qualche minuto e riprova
# 2. Riavvia MySQL
# 3. Aumenta max_connections in my.cnf
# 4. Usa persistent connections

# In wp-config.php per debug
define( 'wp_DEBUG', true );
define( 'SAVEQUERIES', true );

“MySQL server has gone away”

# Query troppo lunga o timeout
# Aumenta in my.cnf:
max_allowed_packet = 64M
wait_timeout = 600

Checklist Database Health

# 1. Verifica connessione
wp db check

# 2. Ripara se necessario  
wp db repair

# 3. Ottimizza
wp db optimize

# 4. Pulisci transients
wp transient delete --expired

# 5. Controlla autoload
wp db query "SELECT COUNT(*) FROM wp_options WHERE autoload='yes'"

# 6. Backup
wp db export backup.sql --add-drop-table

Database troppo grande o lento? Potrebbe servire un’analisi delle query lente o una migrazione a un server più performante. Contattaci per una consulenza.