Codeigniter/PHP check if can connect to database Codeigniter/PHP check if can connect to database codeigniter codeigniter

Codeigniter/PHP check if can connect to database


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.


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.


Based on what was said here:Codeigniter switch to secondary database if primary is down

You can check for the conn_id on the $db_obj

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

This should work.