Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database Switching

I am using mysql I want to use the database for example which is located in server A and when if my connection is lost from server A it should automatically switch to my localhost database and when it is connected again it should switch to server A.

like image 204
Vysakh Avatar asked Dec 06 '25 16:12

Vysakh


1 Answers

If you are using just mysqli extensions, you should use this code to try to establish connection to server A first and if it fails fallback to server B, it will check connection to A server everytime the page loads.

<?php
$con = mysqli_init();
// set a timeout here, the time is in seconds, and this will affect both connections attempts (or more if you want).
$con->options(MYSQLI_OPT_CONNECT_TIMEOUT, 2);    
if(!$con->real_connect("serverA.localdomain:3306","root","password","dbname"))
{
  /* server A not connected */      
  if(!$con->real_connect("serverB.localdomain:3306","root","password","dbname"))
  {
    die('Cannot connect to server A or B');
  } 
  else
  {
    echo 'Connection established to server B';
  }
}
else
{
  echo 'Connection established to server A';      
}

// do your stuff here using $con->...   

$con->close();
?>
like image 97
GChiappe Avatar answered Dec 08 '25 09:12

GChiappe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!