Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter/PHP check if can connect to database

I'd like to backup my read replica(i.e., slave) database with my master database but this simple boolean I did failed:

$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 terminating my read replica database I expected the boolean to evaluate to FALSE and the script to then use my master database. Unfortunately, instead I got the following PHP error:

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

All i want is for the connection to return true or false, does anyone know how to do this in Codeigniter?

like image 701
tim peterson Avatar asked Sep 18 '12 19:09

tim peterson


2 Answers

My question was answered on this thread on Codeigniter forums.

The key is to not autoinitialize the database:

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

To suppress errors it you can set this

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

Then in your code that checks the db state, check TRUE/FALSE of the initialize() function:

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

Here is my entire config file for future reference: https://gist.github.com/3749863.

like image 195
tim peterson Avatar answered Oct 30 '22 10:10

tim peterson


when you connect to database its returns connection object with connection id on successful condition otherwise return false.

you can check it to make sure that database connection is done or not.

$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.';
}

try this and let me know, if you have any other issue.

like image 3
Rajen K Bhagat Avatar answered Oct 30 '22 11:10

Rajen K Bhagat