Codeigniter/PHP check if can connect to database

62,513

Solution 1

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.

Solution 2

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.

Solution 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.

Solution 4

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;

}

Solution 5

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';
Share:
62,513
tim peterson
Author by

tim peterson

web programming-javascript, php, mysql, css, html-is my thang

Updated on July 09, 2022

Comments

  • tim peterson
    tim peterson almost 2 years

    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?

    • Iberê
      Iberê over 11 years
      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.
    • tim peterson
      tim peterson over 11 years
      I know this but how to have it use the 2nd config hostname instead of throwing the error?
    • tim peterson
      tim peterson over 11 years
      @wes can you provide an answer demonstrating try/catch?
    • Iberê
      Iberê over 11 years
      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.
    • tim peterson
      tim peterson over 11 years
      @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.
    • Iberê
      Iberê over 11 years
      var_dump($db_obj) displays what? you can also try to conbine the db_errors with karka91's approach by calling $db_obj->call_function('error')
    • jodi
      jodi almost 10 years
      have do this, but it take long time! stackoverflow.com/questions/23743374/…
  • tim peterson
    tim peterson over 11 years
    -@karka91, thanks, can you explain why you included @ in front of $CI?
  • karka91
    karka91 over 11 years
    PHP error is not an exception and cannot be catched. Though, that might not be the case if CI converts all errors to exceptions
  • tim peterson
    tim peterson over 11 years
    -@wes, unfortunately that didn't work, any other suggestions?
  • karka91
    karka91 over 11 years
    @ 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
  • tim peterson
    tim peterson over 11 years
    hmm, what's call_function()? can you show in your answer where I should put mysql_error?
  • wesside
    wesside over 11 years
    You can catch db errors. In that case, codeigniter can f off.
  • karka91
    karka91 over 11 years
    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)
  • tim peterson
    tim peterson over 11 years
    $readReplica->call_function('error') !== 0 is not the right syntax. Would you mind looking through Codeigniter to find the correct error code?
  • tim peterson
    tim peterson over 11 years
    the var_dump isn't outputting anything
  • karka91
    karka91 over 11 years
    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
    karka91 over 11 years
    well then you'll have to do some research on your own on how to check if the connection made by CI db wrapper was successfull
  • wesside
    wesside over 11 years
    @karka91 Ya well, that's a deal breaker.
  • Arun Jain
    Arun Jain almost 8 years
    Hi, the link of codeigniter forum is not working. Plz suggest alternate url. Thanks.
  • tim peterson
    tim peterson almost 8 years
    The forum isn't necessary for understanding. I included it simply to credit the original authors.
  • reignsly
    reignsly almost 5 years
    $this->database->load must be $this->load->database
  • party-ring
    party-ring over 4 years
    Could you add any explanations to your answer please? :)
  • Omkesh Sajjanwar
    Omkesh Sajjanwar over 4 years
    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);