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.
Javatechig
Lovely. You saved my day.
CE
Thank you!!!!!!!! Worked like a charm!!
Mark Larson
You’re so helpful! All my writing was saved! Yes, I need to do a backup… I did one! Thanks so much, this is just the resource I needed. Luckily Google pulled it right up.
Michael Simoni
I have a test wordpress installation on my home computer running on fedora. I moved/reinstalled the computer with a recent copy of fedora. I restored the database and the wordpress installation. Everything should have been fine except I had the “cannot connect to the database” error. I have had this wordpress installation for a long time. Turns out that when I moved to the new server I also got a new my.cnf. Now I checked it and made everything the same but for some reason i did not add the following line in /etc/my.cnf. Maybe i just wanted to see what would happen. hmmm…what does this button do…..
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1
After I added that line, the database connection problem was fixed.
So I need to drop that user and recreate it with the new password format.
Note I also have
skip-networking
in /etc/my.cnf and….it works. That keeps mysql off the network, including 127.0.0.1. It’s just one less entry point for the mischief-makers.
Matt
I had a database-connection-error on a client’s site and could access the database via PHPMyAdmin but running the testconnect.php file suggested above came up with a response unlisted in this article:
“PHP Warning: mysql_connect(): No connection could be made because the target machine actively refused it.”
I got in touch with Fasthosts who my clients were with and it turned out that they had issues integrating PHP5.4 “and the only fix is to reset the MySQL database user password.”
So if you’re in that boat, then you may be able to fix it by accessing the database via PHPMyAdmin and running the query:
SET SESSION old_passwords = 0;
SET PASSWORD = PASSWORD(‘databasepasswordgoeshere’);
!! IMPORTANT NOTE !! : make sure you get ‘databasepasswordgoeshere’ correct otherwise you’ll be resetting your db password to something new rather than the same password and it could break your site even further!
Terry
I must be really dumb! i understand a little of wordpress but this all sounds way out of my leage.
I have tried to do exactly what you have said and this is what I get
Warning: Cannot modify header information – headers already sent by (output started at /customers/8/a/3/chigwelltkd.com/httpd.www/wordpress/wp-config.php:2) in /customers/8/a/3/chigwelltkd.com/httpd.www/wordpress/wp-includes/functions.php on line 2801
Error establishing a database connection.
I have no idea what to do next!!!
Not only have i lost the site from the web but I know cannot get in to wordpress admin.
IS THERE ANY HOPE!!!!!
WPBeginner Support
Undo the changes by accessing your site through FTP.
Administrador
Rowan Weismiller
Thanks so much for writing this post, it saved me quite a bit of time and a lot of headaches. Cheers!
SH
Solved my issue in less than 10mins cause of this article
YOUR ARE DOPE…you mean business
Thanks a mil!!!
alin
thanks man it’s worked!
Diana
thanks. very good article
Nayonika
This tutorial has really helped solving my problem!! Thanx a ton!
Lyndsay
Thanks a lot, this helped me fix my websites!
Sumi Ghosh
Hi,
Recently i uploaded a theme to the wordpress site, i have also uploaded the local database. I have modified my wp-config file too. Still i am getting error database connection error. When i opened my wp-admin it redirecting to wp-login.
Can i know what might be the problem?
WPBeginner Support
We think its normal behavior for wordpress to redirect you to wp-login.php when you try to access wp-admin directory. Can you please explain further? have you checked your wp-config.php file? does it have your live site’s database information?
Administrador
Aliesha
I had 4 sites give a 127.0.0.1 “Cannot connect to server” message & I also had no access to admin. I went through troubleshooting, & nothing helped. So, I contacted my web-hosting service, Bluehost, to inquire whether the MySQL server was responsive. The tech told me to login to my control panel’s File Manager, select “Show hidden files,” and then to go inside my root directory for each domain & rename my .htaccess file to .htaccess.old . He said he guessed that a plugin added code to my .htaccess file, causing my wp-admin to redirect to an IP address. It worked.
WPBeginner Support
Glad that it worked. However, you should find the plugin responsible for that and delete it.
Administrador
Erik de Vries
Just got this error on my own website. wp-config.php was allright. PhpMyAdmin could load the database. When trying to open the wp_options table PhpMyAdmin said the table must be repaired. Using the repair function in PhpMyAdmin fixed the table, reporting one row had been removed (not saying which one). No clue as to what caused this.
Thanks for the article, helped me debug the error.
Ben
Just got this problem, checked db through host cPanel and admin user seems to have been removed from database assuming that is why wp cannot connect. Problem is my ftp also seems to have been knocked out so i am unable to apply any solutions! sub-domain seems to still be working. It’s difficult to imagine this as being anything other than malicious!
WPBeginner Support
Contact your web host for support.
Administrador
Zimbrul
I just got this problem with one of my sites and fixing the database from wp-config.php did not work. I fixed it by upgrading to WordPress 3.6.1 in cPanel (Softaculous).
Kyra Dawson
Thank you guys! Great How To article!
Ike
Today, for some reason my site is facing the database connection issue.
• Confirmed my database access is working via testconnection.php.
• Changed the salt keys with new ones.
• Defined the proper site URLs to ‘WP_HOME’ and ‘WP_SITEURL’
• No issue with server slowness as my other websites in other root directories are working.
I’m guessing it may be a plugin recently added?
How do you properly uninstall a plugin if you can’t pull up both wordpress root and wp-admin directories in the browser?
Thanks in advanced.
Editorial Staff
Refer to this article:
https://www.wpbeginner.com/plugins/how-to-deactivate-all-plugins-when-not-able-to-access-wp-admin/
Administrador
Anudeep
Thanks a lot for such a good article!
My problem was a bit different. I had this issue because of ‘clicky analytics’ plugin.
I almost went mad as i didnt have any idea of what the problem could be. Finally after lot of trial and error i figured out that it was a plugin interference.
Giorgos
Thanks for the post
Is work to me
Naman Agrawal
Huh! sir you deserve an award.
It just worked for me. I was having this problem from last one month and you just served with this.
Thank you very much
Roeland Sanctorum
Problem occured when requesting new password and didn’t realise this was going to create a db problem. Fortunately I found your comments and guidelines. Problem solved in 3 minutes.
Thanks again (now I’ve subscribed to your weekly email)
Editorial Staff
Thanks Roeland Glad we were able to help.
Administrador
Tamela
My problem happened when I moved the site to a new hosting. I’d altered the config file to match my new database, username & password. But nothing worked.
Your tip about checking the WP-admin page did the trick. It told me something was wrong with the username. I went into c-panel and realized I hadn’t tied the user to the database. Two seconds later, all was good!
You potentially saved me hours of testing the wrong things! Thanks!
Editorial Staff
Glad we were able to help
Administrador
Stu Farrimond
I want to give you a big kiss.
VERY useful.
However, my issue seemed a little odd – and it might help someone else:
This morning our domain produced error:
Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 30720 bytes) in /home/gurumaga/public_html/wp-admin/includes/class-wp-list-table.php on line 384
I tried to increase PHP memory allocation.
Added to wp-settings (in root folder):
define(‘WP_MAX_MEMORY_LIMIT’, ‘256M’);
resulted in:
‘Error establishing a database connection’
Removed line and added lower limit:
define(‘WP_MEMORY_LIMIT’, ’64M’);
resulted in:
‘Error establishing a database connection’
Removed all changes in wp-settings.php now as original.
‘Error establishing a database connection’ persisted (for 5 – 10 mins)
Before reverting to the original error:
Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 30720 bytes) in /home/gurumaga/public_html/wp-admin/includes/class-wp-list-table.php on line 384
I increased the PHP memory limit to: define(‘WP_MEMORY_LIMIT’, ’64M’); again
Then ran the database repair as you advised.
Although no database errors were identified, the site is now back up and running.
Odd – I’m not sure if you or anyone else can make sense of it??
Jamila
THANK YOU.
Editorial Staff
You are welcome
Administrador
Donatus
Thank you so much, i have repair my own and is working perfectly. my site is back
Michael
Embarrassed… I tried everything in this blog and was double checking everything…
It never occurred to me that I’d typo’ed when entering the password.
Doh! So, here’s a +! for double checking the basics
Shaqinah
Hi, I made the mistake of changing the home url, initially it was http://shaneynayguns.com/wordpress and the site url was: http://shaneynayguns.com/wordpress too. I then changed the site url to http://shaneynayguns.com (thinking that that will make my site go live, as you can tell I’m an absolute idiot at this). Nothing happened, so genius here, changed the home url to shaneynayguns.com. That’s when things start to go awry: I couldn’t log in to wp-admin anymore and going to .com/wordpress redirects me to an error page. (shaneynayguns.com remain unchanged and directs to a landing page) I then went on to a forum and followed the exact instructions which were:
1. go to phpmyadmin
2. go to the correct database
3. browse wp_option
4. edit site url (I changed it to .com/wordpress)
Apparently based on everyone’s comments, it worked for all of them… except me! shaneynayguns.com/wordpress now redirects to a page with “error establishing a database connection”! It’s driving me mental! I was hoping if any of you could help me with this. As is obvious, I have not a clue when it comes to web jargon so I would really appreciate a simplified solution. Yes I’m an idiot, and I terribly need help! (F.Y.I: I host on godaddy)
Thanks in advance!
Editorial Staff
Open your wp-config.php file and add this:
1-click Use in WordPress
Administrador
Anderson Tagata
Hey, this worked for me. My wordpress website is on Godaddy and i was trying to put inside of subdirectory. now it works. Just after this, show up some database upgrade screen then everything is fine. also, i took out these defines above and still working. thanks.
Zac
Thanks heaps for your info guide, helped me fix my problem.
To let you know my resolve, I could not see a typo in the wp-config.php but decided to delete my Database and linked Username. I then created new ones and manually updated the new data into the wp-config and boom straight in. One thing to note is the database and username were originally the same name, so not sure if that was an issue as its a new site.
Seth
My website is down and I keep getting “Error establishing database connection” message.
I checked my WP-Config.php page and it looks fine on the inside, but when I preview it, the page says this
Warning: require_once(reddoorplayhouse.com/open/wp-settings.php) [function.require-once]: failed to open stream: No such file or directory in /hermes/waloraweb096/b619/moo.reddoor1/wp-config.php on line 95
Fatal error: require_once() [function.require]: Failed opening required ‘reddoorplayhouse.com/open/wp-settings.php’ (include_path=’.:/usr/local/lib/php-5.2.17/lib/php’) in /hermes/waloraweb096/b619/moo.reddoor1/wp-config.php on line 95
What does that mean. And what can I do? Thanks for your help.
Michael Tidwell
This is a frustrating problem that has been happening multiple times to a few of my sites over the past few weeks. I can fix it easily enough by replacing the Unique Keys and Salts in my wp-config.php file (grabbing new ones at: https://api.wordpress.org/secret-key/1.1/salt), but then days later I have to replace them again… so while I can fix the symptom, I’m still trying to determine why this keeps happening at http://brioagency.com
Editorial Staff
This can be caused by a plugin that you have if it is messing with your settings.
Administrador
manesh
Thanks a lot man, repairing the database fixed my issue!
Andrew Stark
Hi
Just thought I’d thank you for helping me fix a site.
Changing localhost to the database IP address fixed my issue.
Thanks
Andrew
Editorial Staff
Thanks for leaving a comment Andrew. Glad to help
Administrador
Madhurie Singh
I had made copies of the files and saved them on the server.
So when today the database connection error occured, I relaized, I had changed user, , pwd, database access but nothing worked.
So renamed the current wp-config.php as wp-configold.php
and copied the wp-config.php from the archive and pasted as wp-config.php.
Voila it works.
Michael Stelly
Forgot that the database is “local” to the application. I used the site URL by mistake. Switched DB_HOST to ‘localhost’ and all is golden.
Thanks for the blog! +1
Ben
You know sometimes you just find the perfect resource and it answers all your questions. I tip people for pouring me a cup of coffee. I wish it was super easy to just put a buck or two in the wpbeginner tip jar right now, but I guess a thanks will have to do.
Editorial Staff
Thanks Ben. Its always our pleasure to help. The best way to thank us is by spreading kind words about our site or by simply sharing this article on twitter, facebook, etc
Administrador
jAMIE
WP Beginner is just awesome & so is Syed! I don’t know how many times my search results have let me to your site and each time, I’ve learned something really helpful, useful, & practical.
This time, with my database connection error issue, I just had to clear my browser’s cache. FML Anyways, that was the advice that I got after contacting my host. It seems to have worked & hopefully that’s all it takes! How to prevent it from happening again is above me.
Mibo
All I have to say: “THANK YOU!” your post fixed my issues and spared me a couple of hours of work.
Fre
For me the issue was solved by properly setting “siteurl” and “home” in wp_options table did the trick for me, I could log into my admin and change everything!
One day I’ll buy you a cookie!!
Julie Anderson
I have a big problem… i did not set the site up and do not have axxess to the php or any files. i was trying to add pages and the next time i visited the site there was the error. Do i need to get to the admin initiator etc, is there no other way into the site?
Editorial Staff
You need to have admin access to the site.
Administrador
umar satti
You are My HERO
Stephen Doxsee
I get this error intermittently. Perhaps I don’t have enough resources on my amazon ec2 free tier instance. I’ve had the problem 3 times in the last week but have been able to solve it each time by restarting the database server.
Thanks for the post
udumbuke
For me issue was solved by properly setting “siteurl” and “home” in wp_options table
Mana
Thank you so much, Udumbuke. This was exactly the step I forgot in moving my site to a new host. I’m so glad I can stop headaching over this! And great guide altogether on this site.
Joyce Keller
This error happened to me because I wanted to back up my database and could not remember the password. I changed the password in GoDaddy – but this didn’t change it in the wp-config.php! Once I changed it in wp-config, everything worked okay again.
THANK YOU FOR SUCH A COMPREHENSIVE SOLUTION!!! And a truly useful site. Kudos!
JD
In step review of wp-config.php you have to consider the user name and password that is there in the file, the user may not exist in the database (mysql), the password has changed so check if there is the user. In case the user does not exist in the database create it, assign the password found in wp-config.php and provide permits for administration of the database (DBA).
This happened to me to restore my wordpress.
Oliver Wieland
Thanks dude! Restored my database and all i needed to do then was reassign the correct user with the correct database in cpanel.
Pat Walsh
Hi guys, thanks for this info.
Helped me to fix a problem with a WordPress site I created.
It had been happily running for over a month when it started having the “Error Establishing a Database Connection” error.
Finally fixed it by changing DB_HOST to use the full host name rather than the ‘localhost’ that had been in there before.
I don’t know why it worked initially and then stopped working. But its working now…
Cheers,
Pat Walsh
Forma
Having the same connection to DB problem, and after reading comments, I decided to change the wp.config file refrence to my actual host to localhost and for some reason that fixed it. So my solution was the opposite to the one above. Just a shot in the dark…
arman
it is indeed helpful for me as i m facing this problem currently… thanks for this great article..
Arifur Rahman
I’m getting this issue temporary at my site just for few seconds.
how can I be free from this?
Please help!
Editorial Staff
Find the root cause. It can be caused by a plugin. Or simply you need to upgrade your hosting plan if you are getting tons of traffic.
Administrador
Arifur Rahman
Thank you,
I already upgrade my hosting plan from basic to Pro.
But still same as before.
I using Adminimize, AG Custom Admin, Akismet, BuddyPress Template Pack, Display widgets, Fast Secure Contact Form, Google XML Sitemaps, Jetpack by WordPress.com, Page Views Count, Polldaddy Polls & Ratings, User Switching, Better WP Security, BuddyPress, Hotfix, W3 Total Cache, wordPress Importer and WordPress SEO.
Which one is making problem??
Have you any Idea?
Eduardo Capanema
If you have all the info in the config file correct and is still having the problem, check to see if you have any spam prevention plugin active such as Fail2Ban. I found that it was causing the database problem. I believe it happens cause when you’re editing the wordpress via wp-admin, you make too many sequence requests to the apache it triggers the Fail2Ban service for www-data user. Try uninstalling Fail2Ban or any other spam controller. Then, restart both mysql server and apache to get hid of the Error message.
I hope this helps.
b
Stefano
Thank you guys. Problem solved. Very good post