Test connection to the database

3

I have an application that has a central database, in it is made the registration of several databases dynamically to use in another part of the application. I want to know how to test if there is a connection to this database.

I currently have this function in helper to make it easier to setup:

function configure_database($database, $username, $password) {
   $db['hostname'] = 'localhost';
   $db['username'] = $username;
   $db['password'] = $password;
   $db['database'] = $database;
   $db['dbdriver'] = 'mysql';
   $db['dbprefix'] = '';
   $db['pconnect'] = FALSE;
   $db['db_debug'] = TRUE;
   $db['cache_on'] = FALSE;
   $db['cachedir'] = '';
   $db['char_set'] = 'utf8';
   $db['dbcollat'] = 'utf8_general_ci';
   $db['swap_pre'] = '';
   $db['autoinit'] = TRUE;
   $db['stricton'] = FALSE;
   return $db;
}

Now when I connect, I do the following:

$database = $this->load->database(configure_database($name_database, $user_database, $password_database), TRUE);

Is there any way to test the $database variable to check if a connection exists or if there was an error to validate the database record?

Remembering that it is a system that connects to multiple databases and these database configurations are not fixed and can not be left in a fixed array.

    
asked by anonymous 18.06.2015 / 21:50

1 answer

2

According to this answer in SOEn :

Disable automatic database startup:

$db['autoinit'] = FALSE;

To avoid surprise errors, disable debugging:

$db['debug'] = FALSE;

Use the initialize() function to check:

$database = $this->load->database(configure_database($name_database, $user_database, $password_database), TRUE);
$connected = $database->initialize();
if (!$connected) {
    // ...
}
    
18.06.2015 / 22:17