I have some (model)methods and they connect separately to different databases.
I created two database configs from database.php, loaded them both in the model and created two methods; one connects to DB1, and other to DB2. (sample codes below)
When I replace $this->db by $DB1 or $DB2, I'm getting errors like:
Message: Undefined variable: DB1 // or DB2
Else, I get this error:
Message: Undefined property: Home::$db
I tried to include $DB= $this->load->database("database_name", TRUE); in each method to connect to a specific database. It works but I know its not a good practice connecting it again and again as I reuse the method.
I'm really confused.
Below are my codes:
database.php
$db['db1'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db1',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
$db['db2'] = array(
'dsn' => '',
'hostname' => 'other_host',
'username' => 'root',
'password' => '',
'database' => 'db2',
'dbdriver' => 'mssql',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Model:
function __construct()
{
parent::__construct();
$DB1= $this->load->database("db1", TRUE);
$DB2= $this->load->database("db2", TRUE);
}
public function get_from_db1($id)
{
// $query = $this->db->get_where("my_table1",array("ID"=>$id));
$query = $DB1->get_where("my_table1",array("ID"=>$id));
return $query->row_array();
}
public function get_from_db2($id)
{
// $query = $this->db->get_where("my_table2",array("ID"=>$id));
$query = $DB2->get_where("my_table2",array("ID"=>$id));
return $query->row_array();
}
Also:
- Do I declare and load my databases right?
- Where should I put the $this->load->database(); function, in the Controller or Model?
Please help!
Thanks in advance guys!