Is there a version of how to conect to secondary database if primary database is down (PHP) with PDO?
Essentially I want to connect to another database if the primary one fails.
Is there a version of how to conect to secondary database if primary database is down (PHP) with PDO?
Essentially I want to connect to another database if the primary one fails.
Quite simply, you can attempt to connect to the database, and if it fails, connect to the other. Using a try/catch
block and setting the PDO::ATTR_ERRMODE
attribute to throw exceptions, PDO::ERRMODE_EXCEPTION
. Then if the connection throws an exception, catch and and try to connect to the other database.
You will need to test that second connection as well though, as it will - as before - throw an exception if that connection fails as well.
try {
$pdo = new PDO("mysql:host=host1;dbname=host1", 'username1', 'password1', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
} catch (Exception $e) {
try {
$pdo = new PDO("mysql:host=host2;dbname=host2", 'username2', 'password2', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
} catch (Exception $e) {
echo "Connection failed to both databases";
exit;
}
}