6

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?

7
  • Connecting manually to a database in codeigniter using the second parameter as TRUE, will return the Database Object on which you can run your queries. If the connection is denied for some reason, codeigniter will halt your application and throw that error for you.
    – Iberê
    Sep 18, 2012 at 19:48
  • I know this but how to have it use the 2nd config hostname instead of throwing the error? Sep 18, 2012 at 19:50
  • @wes can you provide an answer demonstrating try/catch? Sep 18, 2012 at 19:55
  • Looking at the CI documentation, there is a config option to supress db errors, try adding that to the first config array and see how it goes; the key name is $config['db_debug'] = false; then on the second db config you set it back to true.
    – Iberê
    Sep 19, 2012 at 13:55
  • @Ibere thanks, unfortunately all that suppressing debug errors does is prevent the long timeout and displaying of the error message. It doesn't make the $db_obj return FALSE such that my master database config gets used. Sep 19, 2012 at 14:44

8 Answers 8

12

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.

3
  • Hi, the link of codeigniter forum is not working. Plz suggest alternate url. Thanks.
    – Arun Jain
    Jun 22, 2016 at 15:09
  • 2
    The forum isn't necessary for understanding. I included it simply to credit the original authors. Jun 22, 2016 at 20:42
  • 2
    $this->database->load must be $this->load->database
    – reignsly
    Jun 28, 2019 at 1:15
3

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.

3

I test all I found and nothing wokrs, the only way I found was with dbutil checking if database exists, something like this:

$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
  • Works for me. When I was unable to detect db connection failed using exception handling
    – MdFarzan
    Sep 24, 2022 at 7:20
3

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.

2
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.
}

For those who downvoted me, you can do this. Exception will catch PDOException.

try {

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

} catch(PDOException $e) {

    mail('[email protected]', 'Database error message', $e->getMessage());

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

   exit;

}
5
  • PHP error is not an exception and cannot be catched. Though, that might not be the case if CI converts all errors to exceptions
    – karka91
    Sep 18, 2012 at 19:59
  • -@wes, unfortunately that didn't work, any other suggestions? Sep 18, 2012 at 20:02
  • 1
    You can catch db errors. In that case, codeigniter can f off.
    – wesside
    Sep 18, 2012 at 20:17
  • CI has it's own db wrapper and doesn't use pdo, that's why its firing off errors. You can catch exceptions thrown by PDO, not errors.
    – karka91
    Sep 18, 2012 at 20:46
  • @karka91 Ya well, that's a deal breaker.
    – wesside
    Sep 18, 2012 at 20:51
1
$readReplica = @$CI->load->database($config, TRUE); // ommit the error
if ($readReplica->call_function('error') !== 0) {
    // Failed to connect
}

Im not sure about the error code (not sure if its int/string) and don't have CI nearby to test this out but this principle should work

7
  • -@karka91, thanks, can you explain why you included @ in front of $CI? Sep 18, 2012 at 19:59
  • @ operator hides any errors triggered by the next function call thus the error you get wont be shown. However, you won't know if you connected thats why you should try to call mysql_error to check if the connection is ok
    – karka91
    Sep 18, 2012 at 20:03
  • hmm, what's call_function()? can you show in your answer where I should put mysql_error? Sep 18, 2012 at 20:09
  • you do not need to call mysql_error. CI calls it when you call call_function('error'). Documentation. $readReplica->call_function('error') === mysql_error($readReplica->conn_id)
    – karka91
    Sep 18, 2012 at 20:18
  • $readReplica->call_function('error') !== 0 is not the right syntax. Would you mind looking through Codeigniter to find the correct error code? Sep 18, 2012 at 20:27
1
$this->load->database();

print_r($this->db);
2
  • 1
    Could you add any explanations to your answer please? :)
    – party-ring
    Aug 28, 2019 at 11:18
  • 1.Open database.php file inside folder application->config->database.php 2. edit database.php file $db['default'] = array( 'hostname' => 'localhost', 'username' => 'your mysql user name', 'password' => 'password', 'database' => 'database name' ); 3.inside welcome controller index method we can write //load database libraries $this->load->database(); //call db method inside databse.php print_r($this->db); Aug 29, 2019 at 13:54
1

Its work for me

$config['xxx'] = xx;
        ...    
$config['db_debug'] = false;
$db_obj = @$this->load->database($config,true);
if(!@$db_obj->initialize()){
    echo "Unable to connect database";
    die;
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.