Jordy
Jordy

Reputation: 4809

How to die website if database connection cannot be established

I have a website with a database connection. The connection is very important for the website, so I need to 'die' the website if it can't establish a database connection. The 'or die' isn't a good idea, so I tried this:

$host='localhost';
$un='root';
$pw='mypass';
$dbname='home';

try {
    $db = new mysqli($host, $un, $pw, $dbname);
    if ($db->connect_errno) {
        throw new Exception('Fail: '.$db->connect_errno);
    }
} 
    catch(Exception $e) 
{
    die($e->getMessage());
}

But then, the user can see the error message:

mysqli::mysqli() [mysqli.mysqli]: php_network_getaddresses: getaddrinfo failed: no such host is known

Fail: 2002

What is the best way to check if the connection is ok, and if not: die the website with an error message?

Thanks for the help!

Upvotes: 0

Views: 145

Answers (2)

Manoj Yadav
Manoj Yadav

Reputation: 6612

Log the error and die with custom message

error_log($e->getMessage());
die('custom message');

Upvotes: 0

user4035
user4035

Reputation: 23749

catch(Exception $e) 
{
    die($e->getMessage());
}

Will print a message and terminate the script

Upvotes: 1

Related Questions