Test connection to the database

Asked

Viewed 1,916 times

4

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

Currently I have this function in a helper to facilitate configuration:

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;
}

When the time to 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 variable $database to check if there is a connection or error to validate the database registration?

Remembering that it is a system that connects to multiple databases and these database settings are not fixed, can not leave in a fixed array.

1 answer

2


According to that answer in Soen:

Disable automatic database startup:

$db['autoinit'] = FALSE;

To avoid surprise errors, disable debugging:

$db['debug'] = FALSE;

Use the function initialize() to verify:

$database = $this->load->database(configure_database($name_database, $user_database, $password_database), TRUE);
$connected = $database->initialize();
if (!$connected) {
    // ...
}
  • This solution solved, thanks, as the response of the link needed to change the options of the settings and leave so. $db['db_debug'] = FALSE; $db['autoinit'] = FALSE;

  • Got it. So I’m going to add that answer to help other users :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.