Monday, 26 Oct 2026

Exclusive resources and tools for web design and development experts

Explore
BiblioWeb

Biblioweb.es

All About Web Technology

  • Start
  • WordPress
    WordPress
    • All about WordPress26
    • Plugins de WordPress16
    • Desarrollo web y plugins15
    Rendimiento y seguridad
    • Hosting y rendimiento8
    • Ciberseguridad web7
    • Solución de errores5
    Negocio e IA
    • IA y automatización10
    • WooCommerce y tiendas online6
    Lo último
    Restaurant Menu Widget — WordPress Plugin27 Sep 2026JetStudio Bookings — WordPress Plugin27 Sep 2026SC Heatmap — WordPress Plugin27 Sep 2026
    Ver el blog completoHistorial de noticiasAbout usNewsletter semanal
  • Plugins de WordPress
    Fichas de plugins
    • WP Translate Master
    • Cart Tool Kit
    • SC Heatmap
    • JetStudio Bookings
    • Restaurant Menu Widget
    • WP SEO Pro
    • Rank Math SEO in 2026
    • WP Rocket
    • WPCode
    • AI Engine para WordPress
    Comparativas y guías
    • The best SEO plugins for WordPress
    • The best AI plugins for WordPress
    • The best booking plugins for WordPress
    • WordPress multiidioma
    • Cómo crear un formulario de contacto en WordPress
    • Stripe o PayPal
    Por temática
    • Plugins de WordPress16
    • WooCommerce y tiendas online6
    • Desarrollo web y plugins15
    • IA y automatización10
    • Hosting y rendimiento8
    BibliotecaPlugin Library

    Los plugins de WordPress que desarrollamos: qué hace cada uno, cómo se ve en acción y dónde conseguirlo.

    Entrar en la Pluginteca
    Toda la categoría Plugins de WordPressHerramientas gratis
  • Tools
    Herramientas gratis, sin registro y desde el navegador
    Generador de contraseñasContraseñas largas y aleatorias sin salir del navegador.Generador de QRCódigos QR en PNG de alta resolución, sin caducidad.Contador de palabrasPalabras, caracteres y tiempo de lectura en vivo.JSON FormatterFormatea, valida y localiza el error exacto.WebP ConverterPNG, JPG y PDF a WebP para que la web cargue…PDF a WebPCada página del PDF, en una imagen ligera.Comprobador de emailsSintaxis, correos temporales y registros MX.Compresor de vídeoBaja el peso del vídeo sin subirlo a ningún servidor.Vídeo a MP3Extrae el audio de un vídeo en un par de clics.Firmas de emailFirma en HTML lista para Gmail y Outlook.
    También te sirveHerramientas externas que merecen la pena

    DNS Checker, Query Monitor, Local WP y el resto del kit que usamos a diario, con para qué sirve cada una.

    Ver la selección
    Todas las herramientasPlugin LibraryRecíbelas por correo
  • Plugin Library
  • Español
  • English ✓
  • 🇨🇳 中文(简体)
  • Français
  • Deutsch
  • Italiano
Newsletter
  • WordPress
  • Plugins de WordPress
  • WooCommerce
  • IA para WordPress
  • Security
  • Herramientas gratis
  • See everything
BiblioWebBiblioWeb
Font ResizerAa
  • WordPress
  • Plugins
  • WooCommerce
  • Errores
  • Tools
Search
  • Start
  • WordPress
    • All about WordPress
    • WordPress Plugins
    • Web Development and Plugins
    • AI and Web Automation
    • WooCommerce
    • Hosting and Web Performance
    • Cybersecurity and Web Security
    • Web Error Resolution
  • Plugins de WordPress
    • Rank Math SEO
    • AI Engine
    • WP Rocket
    • WPCode
    • WP Translate Master
    • Cart Tool Kit
    • SC Heatmap
    • JetStudio Bookings
    • Restaurant Menu Widget
    • WP SEO Pro
  • Tools
    • Password Generator
    • QR Code Generator
    • Word Counter
    • JSON Formatter
    • Image to WebP Converter
    • Email Checker
    • Video Compressor for Web
    • Email Signature Generator
    • Video to MP3 Converter
    • PDF to WebP Converter
  • Plugin Library
  • Blog
    • Español
    • English ✓
    • 🇨🇳 中文(简体)
    • Français
    • Deutsch
    • Italiano
Síguenos
© 2026 BiblioWeb — All rights reserved.
Cover » Blog » Error establishing a database connection in WordPress
Troubleshooting web errors

Error establishing a database connection in WordPress

Adrián Alcalá
Actualizado: 08/08/2026 15:04
By Adrián Alcalá
Share
14 min de lectura
Error establishing a database connection in WordPress
SHARE

El mensaje “error al establecer conexión con la base de datos” es de los pocos que WordPress muestra sin rodeos: la web entera desaparece y en su lugar queda esa frase sobre fondo blanco, tanto para tus visitantes como para ti. Significa exactamente lo que dice: el código PHP de WordPress no consigue comunicarse con la base de datos MySQL o MariaDB donde viven tus entradas, páginas, usuarios y ajustes. Sin esa conexión no hay nada que mostrar. Las causas caben en cuatro grupos —credenciales incorrectas en wp-config.php, servidor de base de datos caído o saturado, base de datos corrupta y, con menos frecuencia, disco lleno o un ataque—, y todas tienen solución sin perder contenido. En esta guía las revisamos en orden, del diagnóstico rápido a la reparación, con los fragmentos de configuración exactos que necesitas tocar.

Índice
Qué significa el error al establecer conexión con la base de datosRevisa las credenciales en wp-config.phpCheck the database serverRepair a corrupted databaseOther causes: migrations, hacks, and damaged wp-configQuick checklistHow to prevent the next scareFrequently Asked QuestionsConclusion

Qué significa el error al establecer conexión con la base de datos

WordPress está dividido en dos mitades: los archivos PHP (el motor) y la base de datos (el contenido). En cada visita, PHP se conecta a MySQL usando cuatro datos guardados en el archivo wp-config.php: nombre de la base de datos, usuario, contraseña y servidor. Si cualquiera de los cuatro es incorrecto, o si el servidor de base de datos no responde, la conexión falla y aparece el error.

Primer diagnóstico en 30 segundos: intenta abrir tudominio.com/wp-admin.

  • Si ahí ves un mensaje distinto, del tipo “una o más tablas de la base de datos no están disponibles”, la conexión funciona pero la base de datos está corrupta: salta directamente a la sección de reparación.
  • Si ves el mismo error de conexión en todas partes, el problema está en las credenciales o en el servidor: sigue en orden.

Y una pregunta clave antes de tocar nada: ¿qué cambió justo antes? ¿Migraste la web, cambiaste la contraseña del hosting, instalaste algo? El error rara vez aparece solo; en los common errors when installing WordPress, equivocarse con los datos de la base de datos ocupa el primer puesto.

Revisa las credenciales en wp-config.php

Conéctate por FTP o abre el gestor de archivos de tu hosting y localiza wp-config.php en la carpeta raíz de WordPress. Dentro verás cuatro constantes como estas:

/** El nombre de tu base de datos de WordPress */
define( 'DB_NAME', 'nombre_basedatos' );

/** Tu nombre de usuario de MySQL */
define( 'DB_USER', 'usuario_bd' );

/** Tu contraseña de MySQL */
define( 'DB_PASSWORD', 'contraseña_bd' );

/** Host de MySQL (casi siempre localhost) */
define( 'DB_HOST', 'localhost' );

Compara esos valores con los que muestra el panel de tu hosting (en cPanel: sección “Bases de datos MySQL”; en Plesk: “Bases de datos”). Los fallos típicos:

You Might Also Like

Common errors when installing WordPress and how to avoid them
White screen of death in WordPress: solutions
Yoast SEO: solutions to the 7 most common problems
500 Error in WordPress: what it is and how to fix it
  • Prefijos omitidos: en hosting compartido, el nombre real suele ser usuario_nombre (por ejemplo c1234_wp), no solo wp.
  • Contraseña cambiada: si alguien regeneró la contraseña del usuario de MySQL desde el panel, wp-config.php sigue guardando la antigua. Crea una nueva desde el panel y actualiza la constante.
  • DB_HOST incorrecto: en la mayoría de hostings es localhost, pero algunos (IONOS, SiteGround en ciertos planes, servidores con MySQL separado) usan un host propio del estilo db5001234567.hosting-data.io o una IP, a veces con puerto: 127.0.0.1:3306. El valor correcto aparece en el panel del hosting.

Para comprobar las credenciales sin depender de WordPress, sube por FTP un archivo temporal test-db.php with this content and open it in your browser:

<?php
$conexion = mysqli_connect( 'localhost', 'usuario_bd', 'contraseña_bd', 'nombre_basedatos' );
if ( ! $conexion ) {
    die( 'Fallo de conexión: ' . mysqli_connect_error() );
}
echo 'Conexión correcta';

Si dice “Conexión correcta”, las credenciales están bien y el problema es otro (sigue leyendo). Si falla, el propio mensaje te orienta: “Access denied” apunta a usuario o contraseña incorrectos, y “Unknown database” a un nombre de base de datos equivocado. Delete this file as soon as you finish: contains your password in plain text.

Comprueba también que el usuario tiene permisos sobre la base de datos: en cPanel, en “Bases de datos MySQL”, el usuario debe aparecer asignado a la base con todos los privilegios. Tras una migración es habitual crear la base y el usuario pero olvidar vincularlos.

Check the database server

If the credentials are correct, the next suspect is the MySQL server itself:

  • Server down: on a VPS you can verify it with systemctl status mysql (or mariadb) and restart it with systemctl restart mysql. In shared hosting, you don't have access: check the provider's status page or open a ticket.
  • Saturation due to traffic or queries: a spike in visits, a plugin with heavy queries, or a brute-force attack against wp-login.php can exhaust available connections. The error appears intermittently and disappears on its own: this is the typical pattern. The fundamental solution is caching, optimization, and, if it recurs, a hosting plan with more resources.
  • Full disk: if the server cannot write, MySQL may refuse to work. Check disk usage in the panel: giant logs and accumulated backups are the usual culprits for filling it up.
  • phpMyAdmin as a thermometer: if phpMyAdmin opens and shows your tables, the server is alive and the problem is with credentials or corruption. If phpMyAdmin also doesn't connect, the server is down and the ball is in the hosting provider's court.

Repair a corrupted database

Tables can become corrupted due to an unexpected server restart, a problematic disk, or interrupted writes. WordPress includes an integrated repair mode. Activate it by adding this line to wp-config.php, justo encima de la línea “¡Eso es todo, deja de editar!”:

define( 'WP_ALLOW_REPAIR', true );

Then visit this address in your browser:

https://tudominio.com/wp-admin/maint/repair.php

Verás dos botones: “Reparar base de datos” y “Reparar y optimizar”. Usa el primero (el segundo tarda bastante más). Al terminar, remove the line from wp-config.php: that repair page does not ask for a password and should not remain accessible.

La alternativa manual es phpMyAdmin: selecciona la base de datos, marca todas las tablas y en el desplegable inferior elige “Reparar tabla”. Verás además qué tabla concreta estaba dañada. Antes de reparar nada, si el hosting te lo permite, exporta una copia de la base de datos tal cual está: incluso corrupta, es tu red de seguridad si algo va a peor.

Other causes: migrations, hacks, and damaged wp-config

  • You just migrated the website: 90% of post-migration connection errors are a wp-config.php that still points to the old server's database, or a different DB_HOST with the new provider. Review the four constants with the new hosting data.
  • The site URL changed: this does not cause the connection error, but it is often confused; if the website loads without styles or redirects incorrectly after migrating, the problem is different (siteurl and home in the options table).
  • Attack or infection: there is malware that modifies wp-config.php or deletes tables. If you find strange code in the file, admin users you didn't create, or missing tables, treat the incident as a hack: we guide you in the guide to cleaning a hacked WordPress and in the tricks to strengthen your WordPress security.
  • Restore backup: if you have a recent database backup, importing it from phpMyAdmin (delete damaged tables first) is often the fastest way when repair doesn't work.

Quick checklist

  1. Is the same error seen in /wp-admin? If the message talks about repairing, go straight to repair mode.
  2. What changed just before the failure? (migration, passwords, plugins, updates).
  3. Verify DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST against the hosting panel.
  4. Test the connection with the test-db.php script (and delete it afterwards).
  5. Confirm that the MySQL user has privileges on the database.
  6. Does phpMyAdmin connect? If not, contact hosting: the server is down.
  7. Repair tables with WP_ALLOW_REPAIR and remove the constant when finished.
  8. If nothing works, restore the last backup and strengthen security.

How to prevent the next scare

Once the website is recovered, dedicate ten minutes to preventing it from recurring. Schedule automatic backups that include the database — a daily database backup and weekly file backup is a good starting point — and check occasionally that these backups can actually be restored. Activate page caching to drastically reduce the number of queries reaching MySQL: a cached website can withstand traffic spikes that would bring down the same website without caching. Limit login attempts so that bots don't consume connections, and perform periodic database cleanup (revisions, expired transients, tables of deleted plugins), because a lighter database repairs faster and corrupts less. Finally, write down the current database credentials in a safe place: half the time lost to this error is spent searching for where they were.

Frequently Asked Questions

Have I lost my content if this error appears?

Almost never. The error means that WordPress cannot communicate with the database, not that the database has disappeared. Once credentials are corrected or tables are repaired, all content returns. Actual loss only occurs in severe disk failures without a backup, and that's what the backup is for.

Why does the error appear and disappear intermittently?

That intermittent pattern points to an overloaded MySQL server: too many simultaneous connections due to a traffic spike, a heavy plugin, or bots attacking the login. Mitigate with page caching, block bots, and if it persists, you need more hosting resources.

Does the error establishing a database connection affect SEO?

If it lasts minutes, no. If it lasts days, Google will end up de-indexing pages that return an error. That's why it's advisable to fix it soon and, for long planned outages, serve a 503 maintenance code instead.

Can a plugin cause this error?

It's rare directly, but a plugin can saturate MySQL with massive queries or corrupt its own tables. If the error coincides with the installation of a specific plugin, deactivate it by renaming its folder via FTP and observe if the problem ceases.

Conclusion

The error establishing a database connection is scary because it takes down the entire website, but its diagnosis is one of the most systematic in WordPress: credentials, server, corruption, and in that order. With the four wp-config.php constants verified against the hosting panel, the connection test script, and the integrated repair mode, the vast majority of cases are resolved in less than an hour and without any loss of content. The two lessons to take away: always keep a recent backup of the database, because it turns the worst-case scenario into a mere formality, and when the error is intermittent, don't ignore it: it's a warning that your hosting is becoming too small or that someone is knocking too hard at your door.

Share This Article
Email Copiar enlace Print
ByAdrián Alcalá
Síguele:
Adrián Alcalá es desarrollador WordPress y consultor SEO, autor del plugin WP Translate y creador de BiblioWeb. Desde aquí comparte guías, tutoriales y herramientas gratuitas para quienes crean, optimizan y posicionan páginas web. Lleva años ayudando a negocios de toda España a sacar el máximo partido a WordPress, y todo lo que publica está probado en proyectos reales.
Previous Article White screen of death in WordPress: solutions White screen of death in WordPress: solutions
Next Article How to put WordPress in maintenance mode How to put WordPress in maintenance mode
Ilustración del plugin Restaurant Menu Widget: carta de restaurante con platos y precios editables en Elementor
Restaurant Menu Widget — WordPress Plugin
WordPress Plugins
Ilustración del plugin JetStudio Bookings: formulario de citas por pasos con calendario y bandeja de solicitudes
JetStudio Bookings — WordPress Plugin
WordPress Plugins
Ilustración del plugin SC Heatmap: mapa de calor de clics y scroll sobre una web, con los datos en tu servidor
SC Heatmap — WordPress Plugin
WordPress Plugins
Accesibilidad web en WordPress con IA
Accesibilidad web en WordPress: auditarla con IA en una tarde
AI & Web Automation
BiblioWeb

Biblioweb.es

Web Technology News

Information you can trust: practical web technology guides and solutions — WordPress, plugins, cybersecurity, hosting, performance, and error troubleshooting.

RSS

Enlaces de interés

  • About us
  • Contact
  • Free tools
  • Plugin Library

Recibe nuestras nuevas guías de WordPress en tu correo. Suscríbete a la newsletter.

Legal

  • Legal Notice
  • Terms and Conditions
  • Cookies Policy
  • Privacy Policy

Últimas novedades

Ilustración del plugin Restaurant Menu Widget: carta de restaurante con platos y precios editables en Elementor

Restaurant Menu Widget — WordPress Plugin

27/09/2026
Continue reading
Ilustración del plugin JetStudio Bookings: formulario de citas por pasos con calendario y bandeja de solicitudes

JetStudio Bookings — WordPress Plugin

27/09/2026
Continue reading

© 2026 BiblioWeb — All rights reserved.

Gestionar consentimiento
Utilizamos tecnologías como las cookies para almacenar y/o acceder a la información del dispositivo. Lo hacemos para mejorar la experiencia de navegación y para mostrar anuncios (no) personalizados. El consentimiento a estas tecnologías nos permitirá procesar datos como el comportamiento de navegación o los ID's únicos en este sitio. No consentir o retirar el consentimiento, puede afectar negativamente a ciertas características y funciones.
Funcional Always active
El almacenamiento o acceso técnico es estrictamente necesario para el propósito legítimo de permitir el uso de un servicio específico explícitamente solicitado por el abonado o usuario, o con el único propósito de llevar a cabo la transmisión de una comunicación a través de una red de comunicaciones electrónicas.
Preferences
El almacenamiento o acceso técnico es necesario para la finalidad legítima de almacenar preferencias no solicitadas por el abonado o usuario.
Estadísticas
El almacenamiento o acceso técnico que es utilizado exclusivamente con fines estadísticos. El almacenamiento o acceso técnico que se utiliza exclusivamente con fines estadísticos anónimos. Sin un requerimiento, el cumplimiento voluntario por parte de tu proveedor de servicios de Internet, o los registros adicionales de un tercero, la información almacenada o recuperada sólo para este propósito no se puede utilizar para identificarte.
Marketing
El almacenamiento o acceso técnico es necesario para crear perfiles de usuario para enviar publicidad, o para rastrear al usuario en una web o en varias web con fines de marketing similares.
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Ver preferencias
  • {title}
  • {title}
  • {title}
Accede a BiblioWeb
Usuario o correo electrónico
Contraseña

¿Has olvidado tu contraseña?