El aviso ‘Error al establecer una conexión con la base de datos’ en WordPress es un error fatal que hace que su sitio sea inaccesible para los usuarios. Ocurre cuando WordPress no se ha podido conectar a la base de datos.
Dado que hay múltiples factores que pueden afectar a esta conexión, el error puede ser un poco difícil de diagnosticar para los principiantes.
Llevamos 16 años publicando nuestro blog en WordPress y nos hemos encontrado con una gran variedad de errores y advertencias, como el “Error al establecer una conexión con la base de datos”. Gracias a nuestra experiencia y a muchos periodos de prueba y error, hemos aprendido a diagnosticar estos problemas sin interrumpir nuestro sitio.
En este artículo, le mostraremos cómo corregir fácilmente el “Error al establecer una conexión a una base de datos” en su sitio de WordPress, paso a paso.
¿Cuál es la causa del error al establecer una conexión de base de datos en WordPress?
Una base de datos es un programa informático que facilita el almacenamiento, la organización y la recuperación de datos de otros programas.
Como sistema de gestión de contenidos, WordPress utiliza una base de datos para almacenar todo el contenido y otros datos del sitio web. Se conecta a la base de datos cada vez que alguien visita su sitio web.
WordPress necesita la siguiente información para conectarse a la base de datos:
- Nombre de la base de datos
- Nombre de usuario y contraseña de la base de datos
- Servidor de base de datos
Esta información se almacena en su archivo de configuración de WordPress, que se llama wp-config.php.
Si alguno de estos datos es incorrecto, WordPress no podrá conectarse a su servidor de base de datos y aparecerá el error “Error al establecer una conexión con la base de datos”.
Es uno de los errores más comunes de WordPress. Aparte de unas credenciales incorrectas, este error también puede aparecer si el servidor de la base de datos no funciona o si los archivos de la base de datos están dañados.
Dicho esto, veamos cómo corregir el problema “Error al establecer la conexión con la base de datos” en WordPress diagnosticando paso a paso la incidencia.
1. Marcar / comprobar las credenciales de la base de datos de WordPress
Lascredenciales incorrectas son la causa más común del error de conexión a la base de datos. Si ha trasladado recientemente su sitio de WordPress a un nuevo alojamiento, es probable que este sea el problema.
Las credenciales de la base de datos de WordPress se almacenan en el archivo wp-config.php. Es el archivo de configuración de WordPress que contiene ajustes importantes, incluida la información de la base de datos.
Si no ha editado antes un archivo wp-config.php, consulte nuestra guía para principiantes sobre cómo editar el archivo wp-config.php para obtener más instrucciones.
Busque las siguientes líneas en el archivo 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' );
Aquí debe asegurarse de que la información del nombre de la base de datos, el nombre de usuario, la contraseña y el alojamiento de la base de datos es correcta.
Puede confirmar esta información desde el escritorio de su cuenta de alojamiento de WordPress. Para este tutorial, vamos a utilizar Bluehost, pero el proceso será similar para otros paneles de alojamiento también.
Al acceder, haga clic en la pestaña “Sitio web” de la columna de la izquierda y, a continuación, cambie a la pestaña “Avanzado”. A continuación, desplácese hasta la sección “Base de datos” y haga clic en el botón “Gestionar” situado a su lado.
Esto abrirá la página de Bases de Datos MySQL en cPanel en una nueva ventana.
Aquí, puedes encontrar tu nombre de base de datos y nombre de usuario en la sección ‘Base de datos actual’. No olvide copiar y pegar estos datos en un bloc de notas para poder añadirlos al archivo wp-config.
A continuación, desplácese hasta la sección “Usuarios actuales”, donde podrá enlazar el enlace “Cambiar contraseña” situado junto al nombre de su base de datos.
Esto le llevará a una nueva pantalla, donde podrá cambiar la contraseña de la base de datos a su gusto.
Una vez que haya confirmado todos los detalles de su base de datos, puede cambiar esa información en su archivo wp-config.php si es necesario.
Después de eso, intente visitar su sitio web de nuevo para ver si el error de conexión a la base de datos ha desaparecido.
Si sigue apareciendo el error, significa que algo va mal.
2. Marcar / comprobar la información del alojamiento de su base de datos
Si está seguro de que el nombre de la base de datos, el nombre de usuario y la contraseña son correctos, asegúrese de que la información del alojamiento de la base de datos es correcta.
La mayoría de las empresas de alojamiento de WordPress utilizan localhost como host de su base de datos. Sin embargo, algunas empresas de alojamiento gestionado de WordPress utilizan servidores independientes para alojar las bases de datos. En ese caso, la información del alojamiento de la base de datos no será localhost.
Esto significa que deberá ponerse en contacto con su empresa de alojamiento de WordPress para confirmar estos datos.
3. Reparación de la base de datos de WordPress
Ahora, puede estar recibiendo un error diferente en el panel de wp-admin, como ‘Una o más tablas de la base de datos no están disponibles’ o ‘La base de datos puede necesitar ser reparada’. En ese caso, necesita reparar su base de datos.
Puede hacerlo añadiendo la siguiente línea en su archivo wp-config.php. Asegúrate de añadirla justo antes de la línea ‘¡Eso es todo, deja de editar! Feliz blog”:
define('WP_ALLOW_REPAIR', true);
Una vez hecho esto, puedes ver los ajustes visitando esta página: http://www.yoursite.com/wp-admin/maint/repair.php. Sólo asegúrate de sustituir yoursite.com por tu propio nombre de dominio.
Aquí, debe hacer clic en el botón “Reparar base de datos” para iniciar el proceso.
Nota: El usuario no necesita estar conectado para acceder a la página de reparación de la base de datos. Una vez que haya terminado de reparar y optimizar su base de datos, asegúrese de quitar esta línea de código de su wp-config.php.
Sin embargo, si no desea añadir ningún código a su sitio, también puede reparar su base de datos utilizando el cPanel de su cuenta de alojamiento.
Vaya a su cuenta de alojamiento y abra la página “Sitios web” en la columna de la izquierda. A continuación, vaya a la pestaña “Avanzado” y haga clic en el botón “Gestionar” en la sección Base de datos.
Esto abrirá cPanel en una nueva pestaña. Aquí, desplácese hasta la sección “Modificar bases de datos” y elija el nombre de su base de datos en el menú desplegable “Reparar base de datos”.
Una vez hecho esto, basta con hacer clic en el botón “Reparar base de datos” para iniciar el proceso.
El panel de alojamiento reparará automáticamente su base de datos.
Una vez finalizado el proceso, también verá un mensaje de correcto.
Ahora puede visitar su sitio de WordPress para ver si el error se ha resuelto o no.
4. Marcar / comprobar si el servidor de base de datos está inactivo
Si todo parece correcto y WordPress sigue sin poder conectarse a la base de datos, es posible que su servidor de base de datos(servidor MySQL) no funcione.
Esto puede ocurrir debido a un gran tráfico en el servidor. Su servidor de alojamiento simplemente no puede manejar la carga (especialmente cuando usted está en alojamiento compartido).
Debido a esto, su sitio será lento e incluso puede dar error a algunos usuarios. En este caso, usted debe conseguir en la llamada telefónica o chat en vivo con su proveedor de alojamiento y preguntarles si su servidor MySQL es adaptable.
Además, si usted tiene otros sitios web que se ejecutan en el mismo servidor, entonces usted puede marcar / comprobar esos sitios para confirmar que su servidor SQL está abajo.
Si no tiene ningún otro sitio en la misma cuenta de alojamiento, simplemente vaya a su Escritorio de alojamiento y cambie a la pestaña “Avanzado”.
A continuación, haga clic en el botón “Gestionar” situado junto a la sección phpMyAdmin.
Esto abrirá phpMyAdmin en una nueva ventana, donde debe hacer clic en la opción ‘Base de datos’ en la parte superior.
A continuación, haga clic en el nombre de su base de datos para acceder a sus ajustes. Si puede hacerlo, entonces es el momento de comprobar si el usuario de la base de datos tiene permisos suficientes.
Para ello, debe crear un nuevo archivo llamado testconnection.php y pegar el siguiente código en él:
<?php
$link = mysqli_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($link);
?>
Al pegar el código, asegúrese de sustituir el nombre de usuario y la contraseña por los suyos. Ahora puede subir este archivo a su sitio web y acceder a él a través de un navegador / explorador.
Si el script se conectó correctamente, entonces significa que su usuario tiene permisos suficientes, y algo más está causando el error.
Ahora, debe volver a su archivo wp-config y explorarlo para asegurarse de que todos los detalles son precisos y sin errores tipográficos.
Soluciones adicionales que han funcionado para los usuarios
Si los consejos para diagnosticar problemas mencionados no consiguen corregir el error de conexión a la base de datos en su sitio web, puede probar estos pasos adicionales.
Según informan nuestros usuarios, estos pasos han ayudado a algunos de ellos a resolver el error de conexión a la base de datos en sus sitios web.
1. Actualice la URL del sitio de WordPress
Puede intentar actualizar la URL del sitio de WordPress utilizando phpMyAdmin en cPanel.
Simplemente acceda a phpMyAdmin desde el Escritorio de su cuenta de alojamiento y seleccione su base de datos WordPress de la lista.
A continuación, cambie al menú SQL de la parte superior e introduzca la siguiente consulta MySQL:
UPDATE wp_options SET option_value='YOUR_SITE_URL' WHERE option_name='siteurl'
Debería verse así:
No olvide proporcionar la URL de su propio sitio y cambiar wp_options
por el nombre de su propia tabla, ya que es posible que haya cambiado el prefijo de la tabla de WordPress.
2. Reinicio del servidor web
Los usuarios de servidores dedicados, servidores locales y servidores privados virtuales (VPS) pueden intentar reiniciar sus servidores.
Esto reiniciará su servidor web y de base de datos, lo que puede corregir algunos fallos temporales que causan el error.
3. Pedir ayuda
Si todo lo demás falla, es posible que tenga que ponerse en contacto con su empresa de alojamiento web. Todas las buenas empresas de alojamiento de WordPress le ayudarán a diagnosticar el problema, le indicarán la dirección correcta o incluso se lo corregirán.
También puede contratar desarrolladores de WordPress utilizando una plataforma como WPBeginner Pro Services para ayudarle a corregir este problema por tarifas razonables. Tenemos un equipo dedicado de desarrolladores expertos en los que puedes confiar para resolver cualquiera de tus problemas / conflictos / incidencias en WordPress.
También puede utilizar el servicio para el mantenimiento de sitios, la reparación de sitios pirateados, la optimización de la velocidad, la reconstrucción de sitios web y la optimización SEO.
Esperamos que este artículo te haya ayudado a corregir el problema “Error al establecer una conexión a la base de datos” en WordPress. También puedes consultar nuestra guía práctica para diagnosticar problemas en WordPress o nuestro tutorial sobre cómo añadir una página de error de base de datos personalizada en WordPress.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
Arafat
Sometimes when I click on the “Publish” button to post a new article on my WordPress blog, then this error message appears:
“”Error establishing a database connection… 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 localhost. This could mean your host’s database server is down…..””
Despite the error message appears, my post got published and there is no problem with visiting my site. This error does not come after each post publication. Sometimes it occurs. (My hosting reseller provider changed my server some days ago and this problem began after coming to the new server) What is the problem and how to solve it, please tell …… Thanks.
Editorial Staff
It sounds like that you are having a memory issue on the new server.
Administrador
Quinton
The wp-config.php fix worked for me!! Thanks so much!
Josh
I found a github repo which restarts the mysql server of wordpress if there is a database error using node.js http://goo.gl/gnXLR
Brian Deyo
The quick snippet of PHP you provided was everything I needed to track down my issue.Thanks for the post!
Mario Ben
I am very excited to find this solution. I got the exact problem with my website and after searching it, I found this amazing article.
Thank you so much!
HighHopes
i was using Xampp on local machine to host my wordpress site and got error “Error Establishing the Database Connection”. first time i got that .. not sure why. i noticed in Xampp setup that the user and their privileges was deleted somehow. so i made a new user, using same user name as in ws-config, using host “localhost” and password same as in ws-config. worked like a charm
Olly
You’re a lifesaver. Many thanks!
Karl
I got error but after couple minutes everything got back normal, any way to avoid getting this error in future?
ben
really great post !
helped me revive my wp-blog
thanks !
Demannu
THANK YOU AUTHOR!!! Your little TestConnection script has saved me some serious non-paid time.
MUAH! / HUG / HIGH FIVE
El Hombre
Really, this post has been a last-minute rescue. Many thanks to the editor.
Cheers el hombre
RaDLab
Great article by the way.
My issue is somehow strange to me. In the last couple of days maybe weeks, every morning few of my sites on my server will get the Error establishing connection prompt. But after a few minutes, it starts to work without me doing anything. For example, I will get an email from a client that the Error is showing, but when I quickly check it on my end, it works fine, and The client will also notice it back up. So my problem is strange, I’m not sure what to check if everything seem to resolve itself. Is possible because of high traffic?
Editorial Staff
Your issue is happening due to server overload. While this can mean high traffic, but it doesn’t always mean that. Sometimes, you have medium traffic but a bad plugin that is doing it. Other times, it is just high traffic.
Administrador
RaDLab
Thanks for the response.
This has never happened before. Just today, I’ve had to restart MySQL several times to keep many of my sites running, while I try to figure why it keeps losing connection. I’m really baffled by this. I’ve looked into the php.ini looking for where to increase any sort of limits, but I come up with nothing. It’s running right now, but soon it will fail to connect until I restart MySQL.
Any ideas on how to adjust to the high traffic and keep the MySQL server running?
Editorial Staff
One thing you can do is increase your PHP memory limit. If you are running at 32MB, then that could be a reason. But you will get to a point when your current servers just can’t handle it. You would have to upgrade. Not sure what your server specs are, and how much load you are putting on it.
Run your server logs and see which processes are causing the load. Then see if those can be eliminated or optimized.
XeNNo
I have seen that too myself.
This is happening to me, not only with wordpress but also with joomla and piwik and everything that i use to work with and needs a database.
My provider seems to have a different machine for the MySQL service and every now and then the connection between my sites and the MySQL server drops and give me failure.
You should check that this is your case too… and if so… get another host service
RaDLab
Thanks for your input. I think I have narrowed it down to a db instance that was causing my MySQL to lose connection. It’s an instance running a ELGG system. Soon as I discovered how much load this instance was putting on the server, I deleted it. Since then, the Error has seem to have stopped. Who knew…
aly
for me it was the sql password, which had a symbol ( ] ) at the end.
After giving up on all other “fixes,” I edited the password and presto! All good
yogesh
a very big thanks from me to you because first i website show 500 internel error i fix it by read wpbeginner article now my site show error establishing a database connection i fix it by read your article….thankssssss
mhisyam6
My problem solved from this error just by reinstall/update the wordpress in the dashboard.
Raul
Which version of wordpress did you upgrade to? I was previously on 3.5.1 but read that the 3.5 version is bugged, so I downgraded to 3.4.2. It’s more stable now but I still see the error…
Matt
This has been a question asked by many of our past clients and is such a pain to explain this. Pretty much, 100% of the time I end up having to go in and fix it myself.
Fanto Chandra
I just do repairing the database via cpanel-mysql database and choosing repair database and turn out working and can open the site again now. Thanks for the clue from your explanation.
Christine
my own hosting company couldn’t help me. thank you. the first option worked great.
Alex Patterson
Just went through this issue – and the problem turned out to be that my mysql database was by default using the old 16 byte hashes for the passwords, rather than the 41 byte hashes that the more recent versions of php scripts that Wordpress uses requires.
To see if this is the issue, you can look at your user table in mysql:
select user, host, password from mysql.user;
If the password column for your user is 16 characters rather than 41, that is your issue.
You will need to temporarily set the hashing to 41 digits and then re-encode your password:
set @@session.old_passwords = 0;
set password for ‘wordpress_user’@’localhost’=PASSWORD(‘password’);
Joshua
Just wanted to say “thank you” – this just saved me a ton of time and trouble.
Emdad Shaon
Thanx man……changing mysql password fix my problem…. RESPECT
Joe
Where can I find the password for a mysql database?
Editorial Staff
This is in your cPanel.
Administrador
Jamie
What should I do if it won’t let me log into my cpanel either?
Editorial Staff
Contact your web hosting provider.
Administrador
TP
Great tip I was able to login through backend and reload my site with no more error messages. Took five minutes! Thanks.
Geeky
Thank you, changing password and username worked!
YF
THANKS A LOT!!!!
This really helped me.
Markus
After editing the wp-config.php and updating with new credentials, the error was still present. I had also to clear my APC opcode cache!
Evik
Hi,
thank you for this article. I got this error twice and each time I tried to login into my cpanel it helped. Nothing else, but log into the cpanel resolved my problem.
It does not make sense, and I have no idea what is going on.
I got the message every time after I have made some changes on the website (the last time I was putting on a new email subscription).
Ben Nafi
Thanks sharing..
Thats helped me..
Rae
Aside from updating wp-config.php, I had to update the domain for the following tables:
wp_blogs
wp_site
wp_options -> option_value (for option_name siteurl, home)
If you use WPMU, you will need to update ALL wp_options tables.
The error would NOT go away until all of this was done.
sara
This happened to our site the other day, we got the dreaded error! We received a large amount of traffic but it was expected. We were using Quick Cache as the plugin and the hosts changed it for Super cache and also told us we had hit MySQL max_user_connections due to the queries on the wp_options table. They told us after installing super cache it’s taken us from 600+ database connections to under 5.
After installing the super cache plugin everything worked great again. Now I am concerned about this happening in future, what can I do to try and prevent this? We will always have a large surge in tarffic and then very quiet moments. How can I be sure the database will be able to cope with such demands?
Thanks
smithers
i had “error connecting to database” problem twice in the past two days on a wordpress site on an amazon ec2 micro instance. it occurred after sending out a blast email regarding a fund raising campaign and asking people to check out the site, so i assume it was a load-related failure. anyway, the first time it occurred, i tried to restart the database (service mysqld restart), and it shutdown OK but wouldn’t restart. i then restarted apache (service httpd restart) and then restarted the database, and the database and site came back up.
the problem occurred again today, and the database restart worked without having to restart apache.
Editorial Staff
Are you using a proper caching solution? This shouldn’t happen unless you are receiving a crazy load of traffic.
Administrador
Jon
The scenario you describe is almost certainly caused by your EC2 instance being out of available memory. When you restart Apache a huge chunk of memory is released; only the minimum resources required to get the server up and running are re-allocated when Apache comes back up, then mysqld has plenty of elbow room to start.
A few good places to start fixing this:
1. Check your php.ini memory limit
2. Check your innodb_buffer_pool_size setting in my.cnf
3. Check your swap space
Jamie
I’m running an Amazon EC2 instance also & restarting apache & then restarting mysqld worked for me too.
Daniel
I was moving some webspace from an older to a newer server and tested some things, got stuck with this error. This helped, thanks a lot:
update wp_options set option_value=’http://www.newsitename.de’ where option_name=’siteurl’;
Shawn
Thanks a lot! I was waiting for support from my host for hours…Sundays…but they took too long. My problem was my database password in wp-config, which was different from the real password. I changed it and everything is fine again.
*bookmarked
hanneng
recently I also face the same problem on my blog at http://www.hanneng.net after moved to a VPS.
the solution is to modify the wp-config.php
define(‘DB_HOST’, ‘localhost:/tmp/mysql.sock’);
tristan
Thank you so much! I had messed around in my functions php and lost the ability to open my website. in the process of trying to fix this issue I changed my password for database access and had no idea it was the cause for my error establishing database connection. I’m sure this seems fairly simple to someone who is familiar with this web stuff but for someone like me who is just a dabbler it was very frustrating. website works great now! thank you.
XeNNo
Actually I’ve had a different problem and took me some time to resolve it. My wp after moving from one server to another, editing all files needed (wp-config) started loading on home page nicely. Also the wp-admin section worked like a charm … but still the problem apeared when I started to point on pages and articles … all of theme besides homepage get me the mysql error regarding connection to database….
So…. looking on the internet I’ve found this article of yours and tried your advices … my problem not getting resolved on any of them.
Somehow … don’t know why… my .htaccess file pointed on another default root document and after editing my .htaccess …. everything started to work …
Thought somebody will need that …
Anne
MANY many thanks for posting this. Thought I was going to have to start all over. Being one step above novice is not always sufficient! GAH!
Sean Murphy
Thanks for this post. The adding that line of php code in the first para did the trick for my sites.
Lucy Gage
Hi there,
I am getting this error every day “Error establishing a network connection”. The site was working perfectly, then after the first day I got up in the morning and check the site and saw the error for the first time. I logged into the crazy domains control panel and the database was missing. I called support and it took them all day to fix the problem, but then the site was ok again.
The next morning the same problem again. I called support again. After a couple of hours the site was back working again.
The next morning – the same problem again. another hour speaking to support, but they don’t actually tell me what the problem is.
I am so worried about this and jsut want the problem fixed. Do you think it could be anything I have done whilst setting up the website, or just a problem with the host?
Editorial Staff
It could be a number of things. One of the plugins you are using is exhausting the database server. Another reason could be that your host is overselling the shared hosting plan you maybe on. This would result in database connection error.
https://www.wpbeginner.com/wordpress-hosting/ << See this page if you are looking to find a better web host.
Administrador
Hayley
I actually read half of the 2nd paragraph and managed to fix my site… excellent – thanks.
Editorial Staff
Glad you got it fixed
Administrador
Jenn Hunter
Thank you for writing this article. It helped me when having to reload my WP website from a previous back up.
Damian
What happened with me is the php.config’s password didn’t match..downloading config.php and putting in the proper password fixed it!
Guest
Hi, I run WordPress multisite and just went through an update. I have a blog that has a static front page and a separate page for blog entries. When I tried to open the blog page, I got the above message, Error Establishing a Database Connection.
Turned out I needed to click the yellow bar that appears when you do a major WordPress update, to Update Network which synchs everything database-wise on all sites in your Multisite install. Blog page is viewable now and everything’s working fine!
Rob Rawson
My solution was to install DBVisualizer and what it showed me was that while the dbname was right it was in the wrong case. So changing the db name from wp to WP in my wp-config.php resolved this issue. No idea how this worked in the first place since this was up and running.
Anna Crowe
This was a well written and thorough article. Thank you. Not everything applied to me, but I was able to troubleshoot and identify the problem using some of these suggestions. I’m praising your name today! Thanks.
Jacob Degeling
Hi,
I moved my wp-config.php from the dir below the www root into the www root. That brought the site back up. I would prefer the wp-config.php to be outside the www root, so I’ll have to look into why it wasn’t working in the first place.
Thanks for the help.
Jacob
chris
sql.safe_mode=On in php.ini hosed my multisite install this way. Change it back and the site came up again.
blkbam
One thing to check on if you are moving from your system to the server and using MySQL is the case of the database name. In my situation the server is in all lowercase while my development is all uppercase. Iit’s a very easy over site.
Editorial Staff
Good suggestion
Administrador
Laura
I had this error on my site – i called my host who told me that my username was being denied permission to the database.
No idea how this happened as I hadn’t gone near these details. However, they assured me this was a common problem.
Within 1 minute of the phone call ending, my site was back up and running.
Very strange….but glad its working again!
Great article btw! Glad i didnt need to use it in the end but very easy to understand if i had!
Editorial Staff
Yeah sometimes the cats that work in the servers start having hiccups Glad that your site is working now.
Administrador
RB
My wordpress site was working fine. Then I got the “Error Establishing the Database Connection” message. Doing a Google search, there was a lot of information on what to do. This was the most helpful to me. It ended up that my database options table had crashed. I repaired it per this post and my wordpress site it works fine again. Thanks!
Asif
try checking for the php version as well, sometimes it is the php version on the server that could cause the issue.