Codeigniter / PHP check if you can connect to the database

I would like to backup my read replica database (i.e. slave) with my main database, but this is a simple boolean I made:

$config['hostname'] = "myReadReplicaDatabase.com";
//...$config['other_stuff']; other config stuff...
$db_obj=$CI->load->database($config, TRUE);

if(!$db_obj){
     $config['hostname'] = "myMasterDatabase.com";
     $db_obj=$CI->load->database($config, TRUE);
}

After completing my read replica database, I expected the boolean value to be evaluated like the FALSEscript, to use my main database then. Unfortunately, I got the following PHP error instead:

Unable to connect to your database server using the provided settings.
Filename: core/Loader.php

All I want is a connection to return true or false, does anyone know how to do this in Codeigniter?

+5
source share
7 answers

Codeigniter.

:

$db['xxx']['autoinit'] = FALSE; 

,

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

, db, TRUE/FALSE initialize():

$db_obj = $this->database->load('xxx',TRUE);
  $connected = $db_obj->initialize();
  if (!$connected) {
  $db_obj = $this->database->load('yyy',TRUE);
} 

: https://gist.github.com/3749863.

+11

, : Codeigniter ,

conn_id $db_obj

if ($db_obj->conn_id === false) {
    $config['db_debug'] = true;
    $config['hostname'] = "myMasterDatabase.com";
    $db_obj=$CI->load->database($config, TRUE);
}

.

+3

, false.

, , .

$db_obj=$CI->load->database($config, TRUE);
if($db_obj->conn_id) {
    //do something
} else {
    echo 'Unable to connect with database with given db details.';
}

, .

+3
try { 

// do database connection

} catch (Exception $e) {
  // DO whatever you want with the $e data, it has a default __toString() so just echo $e if you want errors or default it to connect another db, etc.
  echo $e->getMessage();

// Connect to secondary DB.
}

, , . PDOException.

try {

    $pdo = new PDO($dsn, $username, $password);

} catch(PDOException $e) {

    mail('webmaster@example.com', 'Database error message', $e->getMessage());

    // and finally... attempt your second DB connection.

   exit;

}
+2
$readReplica = @$CI->load->database($config, TRUE); // ommit the error
if ($readReplica->call_function('error') !== 0) {
    // Failed to connect
}

( , int/string) CI , ,

+1

, , , , , - dbutil, , :

$this->load->database();
$this->load->dbutil();

// check connection details
if( !$this->dbutil->database_exists('myDatabase'))
    echo 'Not connected to a database, or database not exists';
+1
$this->load->database();

print_r($this->db);
0
source

All Articles