I have to use multiple database connections in my application. The scenario is:
- I have a
dm_masterdb
that holds the database information and the user credentials to login to the app - After logging into the app, this
dm_masterdb
is no more needed, the database information of the logged in user is taken from the database and a connection is made according to his credentials. And now whole application operates on this newly created database connection, sayuserDb
.
Now what I have been doing is:
I have created a the following helper that aids in connecting to the second database:
/**
* Aids in connecting to the passed database
* @param string $db_name database name to which the connection is required
* @return object Database object for the connection made
*/
function connectDb($db_name) {
// Get current Codeigniter instance
$CI =& get_instance();
try {
$userDbConfig['hostname'] = $CI->db->hostname;
$userDbConfig['username'] = $CI->db->username;
$userDbConfig['password'] = $CI->db->password;
$userDbConfig['database'] = $db_name;
$userDbConfig['dbdriver'] = "mysqli";
$userDbConfig['dbprefix'] = "";
$userDbConfig['pconnect'] = FALSE;
$userDbConfig['db_debug'] = TRUE;
$userDbConfig['cache_on'] = FALSE;
$userDbConfig['cachedir'] = "";
$userDbConfig['char_set'] = "utf8";
$userDbConfig['dbcollat'] = "utf8_general_ci";
$userDb = $CI->load->database($userDbConfig, true);
return $userDb;
} catch (Exception $e) {
$error = 'The error thrown is: ' . $e->getMessage();
$error .= 'Error thrown while database connection to ' . $db_name;
show_error($error, 500);
log_message( 'error', $error );
}
}
This function connectDb()
is called in the constructor of each and every model to create a database connection before accessing the database. For example one of my models is given below:
class Payments extends CI_Model {
private $userDb;
public function __construct()
{
parent::__construct();
$this->userDb = connectDb($this->session->userdata('db_name'));
}
public function fetchChartData($period, $type)
{
//...
$result = $this->userDb->query($query);
return $result->result_array();
}
}
Now the question is,
- Is this the right way that I am doing it?
- Is there any way that I can make it more efficient?
- Would it be possible that I can drop off the existing database connection to
dm_masterdb
and access this connection to user's database globally i.e. without having to create database connection in each and every model's constructor?