Home » Php » php – Error establishing a database connection using WordPress

php – Error establishing a database connection using WordPress

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have problem with my WordPress site, it was working normally, Suddenly this message start to appear

Error establishing a database connection WordPress

I tried the following things (no one is working and I still have the same problem till now)

I checked my wp_config.php for db name and credential and every thing is fine and I tried to repair db by adding WP_ALLOW_REPAIR and this scripts shows that every thing is okay.

I added test file to my website to see if the db credentials is correct like following

<?php
$link = mysql_connect('localhost', 'myUserName', 'myPassword');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

and it’s print Connected successfully

I tried to disable plugins by changing the name of the plugins folder, but same problem.

How to&Answers:

Try to change your test file to use the wp-config file.

     <?php
     //PATH TO YOUR FILE
     require_once('path/to/wp-config.php');
     //using wp-config variables 
     $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
     if (!$link) {
          die('Could not connect: ' . mysql_error());
     }
     echo 'Connected successfully';
     mysql_close($link);
     ?>

If this is working you dont have a code issue – you have a server/connectivity issue.

Answer:

1st: Maybe MAX_CONNECTION_LIMIT is the problem. If already max connection open. new connection not accepted. So ur WP Site and other database failed to connect to MYSQL SERVER.

so you will get Error establishing a database connection error.

2nd: Uses of RAM. if your RAM IS FULL. Mysql Server failed to start.

check mysql error logs.

Answer:

Your test demonstrates that you can successfully connect to the MySQL with the user:pass to localhost. But are you sure that the user can use the specific database?
Try to add mysql_select_db( $link, ‘database_name’ ) to your test code, something like this:

<?php
$link = mysql_connect('localhost', 'myUserName', 'myPassword');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';

$use = mysql_select_db( $link, 'myDatabaseName' );

if( $use )
{
    echo "\n" .'Database selected!';
}

mysql_close($link);
?>

This is just a suggestion to be sure that everything is working fine.
As @Nimrod007 said: if everything now is working, the problem is not in the code and could be some server/connectivity issue.