How can I check DB connection is successful or not?

Getting connection error if my database connection is not successful but how can I write custom code to check the connection and do some operation(redirect to an external link or another page) if it’s not connected successfully?

Hello and welcome to our forums! :smiley:

I guess you use laminas-db and there you can try to create a connection:

$adapter = new Laminas\Db\Adapter\Adapter([
    'driver'   => 'pdo_sqlite',
    'database' => 'path/to/sqlite.db',
]);

try {
    $adapter->getDriver()->getConnection()->connect();
} catch (Laminas\Db\Adapter\Exception\RuntimeException $exception) {
    echo $exception->getMessage(); // "Connect Error: SQLSTATE[HY000] [14] unable to open database file"
}

That works for me. I got the connection error message.
Instead of showing an error message how can I redirect to Custom url without using normal php header
try {
$adapter->getDriver()->getConnection()->connect();
} catch (Laminas\Db\Adapter\Exception\RuntimeException $exception) {
/**
Redirect to www.example.com using laminas
header(‘Location: http://www.example.com/’);
exit;
*/
//echo $exception->getMessage(); // “Connect Error: SQLSTATE[HY000] [14] unable to open database file”
}

Hi,

Try this (example for Controller):

$url = 'https://www.example.com';
return $this->redirect()->toUrl($url);

Check this: Controller Plugins - laminas-mvc - Laminas Docs

Redirect requires MvcEvent.