Codeigniter switches to a secondary database if the primary file

I am wondering if there is a way to handle the mysql error and configure ci to switch to the secondary database server in case the primary server is down (cannot connect)?

+1
source share
1 answer

Well, I don't know if this will work, but you can really try this:

1) create 2 groups of database parameters (in the /config/database.php application):

// regular one..
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
//...

// second connection
$db['second']['hostname'] = 'localhost';
$db['second']['username'] = 'root';
//...

2) Set deubg off to avoid db errors and actually kill your script (do this for both):

$db['default']['db_debug'] = FALSE;

3) When loading the library, you can pass TRUE to the second paragraph, so that in fact there is a returned value; it returns the database object itself:

$dbobject1 = $this->load->database('default',TRUE);
$dbobject2 = $this->load->database('second',TRUE);

ID , , :

if(FALSE === $dbobject1->conn_id)
{
  echo 'No connection established!';
}

, . , , db , ...

, , , , , , . ( , 2 ), , :

class Check_db {

     private $CI = '';
     public $DB1 = '';
     public $DB2 = '';

     function __construct()
     {
        $this->CI =&get_instance();
        $this->DB1 = $this->CI->load->database('default',TRUE);
        if(FALSE !== $this->DB1->conn_id)
        {
          return $this->DB1;
        }
        else
        {
          $this->DB2 = $this->CI->load->database('second',TRUE);
          if(FALSE !== $this->DB2->conn_id)
          {
            return $this->DB2;
          }
          else
          {
            return FALSE;
          }
        }
      }
+6

All Articles