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

Så här fixar du error vid upprättande av en anslutning till en database i WordPress

Ser du notisen ”Error establishing a database connection” i WordPress?

Detta är ett fatal error som gör din site otillgänglig för användare. Det inträffar när WordPress inte kan upprätta en anslutning till databasen. Eftersom flera faktorer kan påverka denna anslutning kan error vara lite svårt att troubleshoota för Beginner.

I den här artikeln kommer vi att visa dig hur du enkelt fixar ”Error establishing a database connection” på din WordPress site, steg för steg.

Fix the Error Establishing a Database Connection in WordPress

Vad orsakar error vid upprättande av en anslutning till en database i WordPress?

En database är en programvara som gör det enkelt att lagra, organisera och hämta data från andra program.

Som ett system för hantering av innehåll använder WordPress en database för att lagra all your content och andra data på din website. Den ansluter sedan till databasen varje gång någon besöker din website.

WordPress behöver följande information för att ansluta till databasen:

  • Namnet på din database
  • Database användarnamn och password
  • Server för databaser

Den här informationen lagras i din WordPress-konfigurationsfil, som heter wp-config.php.

Om någon av dessa uppgifter är felaktiga kommer WordPress att misslyckas med att ansluta till din server för databasen och du kommer att se felet ”Error establishing a database connection”.

Database connection error in WordPress

Det är ett av de vanligaste WordPress error. Förutom felaktiga credentials kan detta error också dyka upp om databasens server är nere eller databasfilerna är korrupta.

Med detta sagt, låt oss ta en titt på hur man fixar ”Error establishing database connection” issue i WordPress med steg-för-steg troubleshoot.

1. Kontrollera din WordPress Database Credentials

Den vanligaste orsaken till error i anslutningen till databasen är felaktiga credentials. Om du senaste har flyttat din WordPress site till en new server, så är det troligen detta som är problemet.

Credentials för din WordPress-databas lagras i filen wp-config.php. Det är konfigurationsfilen för WordPress som innehåller viktiga settings, inklusive information om databasen.

Om du ej har redigerat filen wp-config.php tidigare kan du ta en titt på vår guide för nybörjare om hur du redigerar filen wp-config.php för mer instruktioner.

Du kommer att leta efter följande rader i filen 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' );

Här måste du se till att informationen om databasnamn, användarnamn, password och server är korrekt.

Du kan bekräfta denna information från instrumentpanelen för ditt WordPress dashboard. För denna tutorial kommer vi att använda Bluehost, men processen kommer att vara liknande för andra webbhotell paneler också.

När du har loggat in klickar du på fliken ”Website” i den vänstra kolumnen och växlar sedan till fliken ”Advanced”. Rulla sedan ner till sektionen ”Database” och klicka på knappen ”Manage” bredvid den.

Click the Manage button next to the Database section

Detta kommer att öppna sidan MySQL Databases i cPanel i ett new fönster.

Här kan du hitta ditt databasnamn och användarnamn i sektionen ”Current Database”. Tänk på att copy and paste dessa details till ett anteckningsblock så att du kan add to dem till wp-config-filen.

Find your database name and username in the Current Databases section

Därefter rullar du ner till sektionen ”Current Users”, där du kan clicka på länken ”Change Password” bredvid namnet på din database.

Du kommer då till en new vy där du kan ändra lösenordet för databasen så som du gillar det.

Change your database password

När du har bekräftat all din database details kan du ändra den informationen i din wp-config.php-fil om det behövs.

Efter det kan du försöka besöka din website igen för att se om error i anslutningen till databasen har försvunnit.

Om du fortfarande kan se error betyder det att något annat är fel.

2. Kontrollera informationen om servern för din Database

Om du är säker på att uppgifterna om databasens namn, användarnamn och password är korrekta, är det bra att kontrollera att du använder korrekt information om databasens server.

De flesta webbhotell för WordPress använder localhost som server för din database. Vissa hanterade WordPress-värdföretag använder dock separata servrar för att servera databaser. I så fall kommer din databas serverinformation inte att vara localhost.

Detta innebär att du måste kontakta ditt webbhotell för WordPress för att bekräfta dessa detaljer.

3. Reparera WordPress Database

Nu kanske du får ett annat error i wp-admin adminpanelen som gillar ”One or more database tables are unavailable” eller ”The database may need to be repaired”. I så fall måste du reparera din database.

Du kan göra detta genom att lägga till följande rad i din wp-config.php-fil. Se till att add to den precis före ”That’s all, stop editing! Trevlig blogg”:

define('WP_ALLOW_REPAIR', true);

När du har gjort det kan du se inställningarna genom att besöka den här page: http://www.yoursite.com/wp-admin/maint/repair.php. Se bara till att ersätta yoursite.com med ditt eget domain name.

Här måste du klicka på knappen ”Repair Database” för att starta processen.

Repair WordPress database

Note: Användaren behöver ej vara inloggad för att komma åt reparationssidan för databasen. När du är klar med att reparera och optimera din database, se till att ta bort den här kodraden från din wp-config.php.

Men om du inte vill add to någon kod till din site, kan du också reparera din database från ditt webbhotell kontos cPanel.

Gå vidare och besök ditt webbhotell konto, där du måste öppna sidan ”Websites” från den vänstra kolumnen. Gå sedan till tabben ”Advanced” och klicka på knappen ”Manage” i sectionen ”Database”.

Click the Manage button next to the Database section

Detta kommer att öppna cPanel i en new tab. Här rullar du ner till ”Modify Databases” section och väljer namnet på din database från ”Repair Database” dropdown menu.

När du har gjort det klickar du bara på knappen ”Reparera databas” för att starta processen.

Click the Repair database button

Webbhotellets panel kommer nu automatiskt att reparera din database åt you.

När processen är completed kommer du också att se ett success message.

Database repair success message

You can now visit your WordPress site to see whether the error has been resolved or ej.

4. Kontrollera om din server i databasen är nere

Om allt verkar vara korrekt och WordPress fortfarande inte kan anslutas till databasen, kan din databasserver (MySQL server) vara nere.

Detta kan hända på grund av tung trafik på en server. Din server kan helt enkelt inte hantera hämtar (särskilt när du har delade webbhotell).

På grund av detta kommer din webbplats att bli långsam och kan till och med mata ut error för vissa användare. I det här fallet bör du ta ett telefonsamtal eller chattsupport med din hosting provider och fråga dem om din MySQL server är responsiv.

Om du dessutom har andra webbplatser som körs på samma server kan du kontrollera dessa webbplatser för att bekräfta att din SQL-server är nere.

Om du ej har någon annan site på samma webbhotell account, så går du bara till din dashboard och byter till tabben ”Advanced”.

Därefter klickar du på knappen ”Hantera” bredvid phpMyAdmin section.

Click the Manage button next to the PHPMyAdmin option

Detta öppnar phpMyAdmin i ett nytt fönster, där du måste klicka på alternativet ”Database” högst upp.

Därefter klickar du på namnet på din database för att komma åt dess Settings. Om du kan göra det, är det dags för dig att kontrollera om din databas användare har tillräckliga behörigheter.

Connect PHPMyAdmin with your database

För att göra detta måste du skapa en new fil som heter testconnection.php och klistra in följande kod i den:

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

När du klistrar in koden, se till att ersätta användarnamn och password med dina egna. Du kan nu uploada filen till din website och komma åt den via en web browser.

Om skriptet ansluts utan problem betyder det att din användare har tillräcklig behörighet och att det är något annat som orsakar error.

Nu måste du gå tillbaka till din wp-config-fil och skanna den för att se till att alla detaljer är korrekta och utan några stavfel.

Ytterligare lösningar som har fungerat för användare

Om de ovan nämnda felsökningstipsen inte lyckas fixa felet i anslutningen till databasen på din webbplats kan du prova dessa ytterligare steg.

Som våra användare har rapporterat har dessa steg hjälpt några av dem att lösa error i anslutning till databasen på sina webbplatser.

1. Update URL:en för WordPress site

Du kan försöka updating URL:en för WordPress site med hjälp av phpMyAdmin i cPanel.

Gå bara in på phpMyAdmin från din dashboard på webbhotellet och välj din WordPress database från listan.

Följ detta genom att gå till SQL-menyn högst upp och enter följande MySQL sökning:

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

Det ska se ut så här:

Change site URL

Glöm inte att ange din egen site URL och ändra wp_options till ditt eget tabellnamn, eftersom du kan ha ändrat WordPress tabellprefix.

2. Starta om web server

Användare på dedikerade servrar, språkversioner och virtuella privata servrar (VPS) kan försöka starta om sina servrar.

Detta kommer att starta om din web server och database server, vilket kan fixa några tillfälliga problem som orsakar error.

3. Be om hjälp

Om allt annat Misslyckas, då kan du behöva kontakta ditt webbhotell. Alla bra webbhotell för WordPress kommer att hjälpa dig att troubleshoota problemet, peka dig i rätt riktning eller till och med fixa det åt dig.

Du kan också hyra WordPress utvecklare med en plattform som WPBeginner Pro Services för att hjälpa dig fixa detta issue till rimliga priser. Vi har ett dedikerat team av expertutvecklare som du kan lita på för att lösa alla dina WordPress issues.

WPBeginner Pro Services

Dessutom kan du använda tjänsten för underhåll av din webbplats, reparation av hackad webbplats, hastighetsoptimering, ombyggnad av webbplats och sökmotorsoptimering.

Vi hoppas att den här artikeln hjälpte dig att fixa ”Error establishing a database connection” issue i WordPress. Du kanske också vill se vår guide till felsökning av WordPress för tips om hur du löser WordPress issues på egen hand, eller våra expertval av de bästa tools för WordPress frilansare och utvecklare.

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.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

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.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

665 kommentarerLämna ett svar

  1. Syed Balkhi

    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. Riya Mehta

    Hey,

    Today I got the same error and I fixed this by giving all privilege(Permissions) to user under the database defined in configuration file that is wp.config file.

  3. bog

    What happened to me was that my hard drive (linux) spontaneously went into read-only mode. Out of nowhere. I know this is an obscure cause, but nonetheless I thought I’d pitch in. (usually the sign of a dieing drive, I’m told).

  4. Masood Ahmad

    Hi everyone,
    In my case it was very simple. The password for MySQL database and the password in the wp_config.php must be same, ignorant of the fact, I changed the password for mysql database and remained upset the whole day. Until by chance I reverted the change. My site was up and live in the next second.

  5. Jamie

    When i rename index.php to index_.php — then the back end of the website loads up fine

    Pages on the website give a normal ‘Not Found’ Apache error

    ——

    When i restore the index.php filename — then nothing works, and I receive ‘error establishing a database connection’ on public facing pages. And wordpress’ own ’error establishing a databse connection’ text box when I visit /wp-admin

    Any help you can offer will be much appreciated!

  6. Tony thomas

    When you are operating in google cloud, you may often receive this error if your RAM is using more resources.

    login to google cloud

    Find the instance from ’compute engine’. Click on the top menu to find ’compute engine’

    login to SSH

    type sudo bash (to enter as root)

    Then type/copy paste :

    systemctl start mariadb.service (in centos 7)

    error establishing database will be solved instantly.

    • Jarrett

      If you’re using mysql, you can do this

      sudo service mysql restart

      Thanks for the pointer!

      • Sabir Guiri

        It worked perfectly. thank you so much!

  7. Yudha Haris

    Thanks So Much IT’S WORK..

  8. Tim

    Thank you for this article…it’s the most useful on the web I would say.

    I still have the problem anyway (host is Godaddy)…I created the testconnection.php page and i get this error message :

    Warning: mysql_connect(): Access denied for user ’username’@’hostIP’ (using password: YES) in /home/content/n3pnexwpnas01_data02/52/3027952/html/wp-config.php on line 106
    Could not connect: Access denied for user ’username’@’hostIP’ (using password: YES)

    – username being the username I use to connect to database via Phpmyadmin
    – password being the password I use to connect to database via Phpmyadmin
    – hostIP being the hostname value I found in the database variables in Phpmyadmin

    I have been stuck for hours now…can you help me on this ? I have no idea what to do and how to do it…

    Thank you in advance

    • WPBeginner Support

      The most likely reason for this is incorrect information in your wp-config.php file. This could be your MySQL host, username, password, or database name. IF you are using hostname IP, then try adding port to it. Ask your web host for support.

      Administratör

  9. Prashant

    Dear Friends,

    I M New and very little to know about wordpress today i face a prob

    when i try to publish a new post or update the older one and push the button publish or updates its automatically redirected to home page nothing happen not change in updated post not publish a new post please help me if anybody know about such an issue.

    thanks

    • WPBeginner Support

      Try updating permalinks by visiting Settings->Permalinks page and just click on the update button.

      Administratör

  10. Abel

    Hey, thanks, this worked for me, thumps up!

  11. Robert DeRobertis

    Thank you, Thank you, Thank you.

    I was hacked recently and changed the passwords to my website to something more secure. I missed updating the config file. This saved the day.

  12. Cássio Sá

    My friend, i’m having tears of joy right now, you saved my life. The problem was in the config file. I imported the old database and changed the credencials on it, but haven’t changed the credencials in the config file. Thank you very much for the tip.

  13. Ali

    I just change http to HTTPS Now my site is not opening and showing same error please tell me what to do now ?

    • Ryan

      Have you changed the site url in the database in WP_Options table?

  14. feizel

    Thank you so much. i have been searching for the solution like all night.

  15. Paul

    Hey great article about how to troubleshoot database connection errors.

    Might be good idea to link to your old article about making a custom dB error page. Otherwise if utilising good caching program it can take a while before actually realise something is wrong. This article and the mail function means you can be notified instantly and provide a nice image and custom text which is more professional than the default message.

    https://www.wpbeginner.com/wp-tutorials/how-to-add-a-custom-database-error-page-in-wordpress/

  16. stephanie wandke

    Thanks for this article! It was definitely a database user issue and when I added a new user and password, changed the wp-config file, BAM the site was back. You made it easy and I solved my problem in under 15 minutes. Thank you!

  17. Edward

    Godaddy customer. Getting this same issue.

    Database was working fine. What worked for me was to go into wp_config and change the following line:

    define(’DB_HOST’, ’localhost’); [the db_host was something different, not localhost]

    to

    define(’DB_HOST’, ’[my IP address]’) and it worked fine

    Thanks for the tip!

    • Daryl

      This worked for me on my GoDaddy Site

  18. Shakti

    Sir help me please
    My website is loading, and working fine but I get error establishing database connection when I tried wp-admin and again I reloaded page 3-10 times and my site is working. Again I get that error unexpectedly.

    • WPBeginner Support

      It seems that your database server is not responding. Please contact your web host and tell them what’s happening.

      Administratör

      • Shakti

        Ok Thankyou Sir

  19. Shelly

    My site goes down and I get this same error message at the same time every night. It lasts for about an hour and a half, and then the site is back up again. Would that indicate an issue with my hosting service?

    • Harinath

      Did you happen to find any resolution for it?

  20. Liesje

    Thanks a lot for this article ! Piece of cake this way :-)
    Saved me a lot of work and headaches.

    Kinders regards,
    Liesje

  21. praveen

    i have error in wp-admin page. its says Error establishing a database connection. how to solve it .

  22. Ian Wells

    This occurred once for me on my EC2 AWS instance. The cause was I am using a small t2. micro server, and I sometimes got too many httpd requests coming in, especially when I turned on my AWS health checks which increase traffic. I reconfigured my /etc/httpd/conf/httpd.conf per instructions here: https://wordpress.org/support/topic/how-to-optimize-apache-for-wordpress and so far, so good. I no longer see 20 or more httpd processes running at once, followed by out of memory and data base disconnected.

  23. Ian Wells

    This error kept occurring. I could clear it by rebooting EC2 but not very satisfactory. Then I noticed my EC2 installation was out of date, so I ran ”sudo yum update” on the server. Looking much more stable now.

  24. ani

    nice …exhaustive ..detailed information …i fought with my hosting guys and demanded a root cause for slow DB performance /connectivity…these guys kept recommended to upgrade hosting account to dedicated setup ..POST gave insights on probable problems and ways to tackle .

    Thanks !

  25. alexsbutler

    You can also try Kernel for Word file repair tool to repair your corrupted Word file easily.

  26. Ken Pyle

    Thanks for the article. Lunarpages is my host and around 2:30 AM (thanks Jetpack for monitoring my site), my site quit working and I also had the ”Error Establishing Connection to the Database Error.”

    How I fixed the problem was to re-enter the password into the MySQL database (got there via Cpanel). I used the same password that was already in the config file, so that way I only had to change one variable.

    I have tried it on 3 WordPress installs so far and it seems to work, as Jetpack informed me that my site is back up after being down for 16 hours.

    It is a mystery as to why it disconnected.

    • Jason Teale

      I am on Lunarpages as well. So basically, I just have to re-enter the the blog password and that is it? What was the one variable that you changed?

      • Mike B

        I also am on Lunarpages. I also needed to re-enter my password in C-Panel. Something must have happened with Lunarpages this morning.

    • NickP

      Thank you, Ken! Exactly what I needed to know. Back up and running in minutes…

  27. Harm

    I made some changes in wp_user and wp_metadata to create a new admin. Then I get this message. I tried to look at the wp-config-file, but get the same message! What can I do more?

  28. Scott

    Sort of silly looking back at this, but it might help someone else so I think it’s worth sharing. Recently had a site that was set up to use Cloudflare as it’s CDN. All the DNS ”A” records were set except for the one for ”mysql.domain.com”, so even using the testconnection.php trick didn’t work (on Dreamhost that doesn’t use localhost). Simply added the ”A” record in Cloudflare and life was good again.

  29. Sharad Gupta

    An awesome solution for a very difficult and annoying problem .

  30. MaSilat

    Awesome. It helped me and solve DB problem.

  31. Mohamed Azazy

    You can also restart your MySQL service if you’re using VPS.
    – sudo service mysql restart

    Worked for me!

    • Dustin Overbeck

      Thanks for this suggestion. Restarting mysql was the magic bullet in my situation.

  32. Michael D

    Thanks for this article, it helped!

    We had the error occurring in both the root domain and wp-login. Changing ’localhost’ to the IP in wp-config.php fixed it.

  33. Rav

    It appeared my ’localhost’ was not working so I just added the direct address of my hosting provider (mysql.hostinger.co.uk) and everything started working again!

    Thanks for the help!

  34. Christopher

    Actually, I’m getting ”Error establishing a database connection” in my home page only. All other pages are working fine. Please let me know what to do.

  35. Adrienne

    My old client has this issue now, and her site is about 3 years old and hasn’t been updated. I think the theme and all the changes has corrupted this site. It needs to be scrapped and redone…. now, I have to find a simple way to do it. lol

  36. Nicole

    I was moving a multisite system- I had to switch out the old website name in my database, and in the .htaccess and wp-config files

  37. m3d01

    Hello guys,

    I found the problem that my hosting service made update and that lead to change in the DB_HOST number so i change it back by the new one by edit the config file and the site is back again to work finally :)

  38. John Bert

    Recently I have transferred from Arvixe to Phi9 web host.
    Actually I forgot to change the previous host “MySQL Connections Strings” in wp-config.php. Now it’s working.

    Thank you for your great help I really appreciate it! :)

  39. Micky

    I have seen this error. I was putting the wrong MySQL port in connection line. Your post helped me fix it. :)

  40. Carl

    This seems logical. But I go through each step and nothing changes. Why is this so complex?
    I liked the idea of the database repair but it appears that WordPress would need to be up and running to hit the Repair Database button. I’ve been at this for 2 days. Is there a place to go where I can find the problem by looking at some code? This all seems so vague.

  41. Leonard Rattini

    As I worked in computer application design for 30-years, and I’m also registered as a Certified Computer Professional, many people, to impress, use the ”database” term incorrectly.

    Database is a different data retaining methodology than what was use before its time. Back in the earlier days, data was retained on liked related 80-column cards and collectively they were know as a file. For instant many invoice records, collectively were known as the Invoice File. Medical records collectively, were known as a Medical file, etc.

    In early big main frame computer days, before PC’s that came along, they processed these ”80-column fixed-records.” With the advent of the Internet and distributed multiple keyboards, data then was recorded as ”data packets” and they are stored in a ”database,” which is a three-dimensional format structure stored in the computer. Then at the right time, to process, data items needed ”linked’ data packets then allowed for this to happen which then looked like a record we are familiar with.

    An application must be designed as a database base application that includes a Database Administrator person, otherwise its application is not a database application.

    A database application served two main purposes versus the old file methods used in the olden days before the Internet and distributed keyboards. One was to capture data items at first point of (data) entry. And secondly, it is intended to eliminate ”data-redundancy.” Leonard Rattini, CCP (to know of my CCP credentials, google ICCP)

  42. Toby Harding

    I’ve seen this error a few times now, with my WordPress that is hosted on an Amazon EC2 box in their AWS cloud. Simple way to fix the issue is to restart the instance from the AWS admin console.

  43. Jake B

    Thanks for the article. I was able to work through each step until I found my issue.

  44. Unknown

    Hey, i am getting this error while installing wordpress ”Error establishing a database connection” what should i do to get rid of this error .I’ve tried everything like changed database name , deleted previous databases but still wordpress is not is not installed yet. Please help !

  45. David Clarke

    Solved my issue in minutes thanks to this helpful article, thanks a lot!

  46. Friday

    I can’t help it, since i created my site i haven’t touched that area can you help me to do it

  47. mikhail

    Thanks for the article, it helps.
    For me it’s because I change my database user password from CPanel but apparently the wpconfig.php file won’t change automatically when i changed my database user password .

    I have to change it manually in
    define(’DB_PASSWORD’, ’[insert your password here]’);

    • Juan Loayza

      Thks so much! It was a headache … until I found your solution…

    • Tapiwa

      Dude! Thank you so much! I just fixed my website thank to this article and your comment.

  48. Max Demian

    Really useful, thank you.

  49. James Kalmakoff

    The article was very useful and I resolved my Database connection problem. A further place to look for errors is in the MySQL database. Be sure that the ’database_username’ and the ’database_name’ are correctly assigned to each other and that there are no typos!

  50. Dawn

    I just got this error, I copy and Pasted a page to a word document, I saw that there was a paragragh added with ads and links to sites like viagra ect. I removed the ad/links paragragh and re-pasted the text back into my webpage. I was on the second page and posted the updates, when I received this error…any one else had this?

    • J

      Hey – this won’t help your problem, but you shouldn’t be using Word to edit these files. You want to use a simpler program like Notepad/TextEdit etc.

  51. Peter Gough

    Many thanks for this article. Very, very useful.

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.