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. Commented Sep 18, 2012 at 19:48
  • I know this but how to have it use the 2nd config hostname instead of throwing the error? Commented Sep 18, 2012 at 19:50
  • @wes can you provide an answer demonstrating try/catch? Commented 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. Commented 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. Commented 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, the link of codeigniter forum is not working. Plz suggest alternate url. Thanks.
The forum isn't necessary for understanding. I included it simply to credit the original authors.
$this->database->load must be $this->load->database
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.

Comments

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 Comment

Works for me. When I was unable to detect db connection failed using exception handling
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.

Comments

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 Comments

PHP error is not an exception and cannot be catched. Though, that might not be the case if CI converts all errors to exceptions
-@wes, unfortunately that didn't work, any other suggestions?
You can catch db errors. In that case, codeigniter can f off.
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 Ya well, that's a deal breaker.
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 Comments

-@karka91, thanks, can you explain why you included @ in front of $CI?
@ 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
hmm, what's call_function()? can you show in your answer where I should put mysql_error?
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)
$readReplica->call_function('error') !== 0 is not the right syntax. Would you mind looking through Codeigniter to find the correct error code?
|
1
$this->load->database();

print_r($this->db);

2 Comments

Could you add any explanations to your answer please? :)
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);
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;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.