php - Connecting two database in codeigniter not working -
i trying connect 2 database in codeigniter. came accross link codeigniter - multiple database connections , setup database per requirements. problem default database active. here's code
model
function __construct() { parent::__construct(); $this->db_2 = $this->load->database('database2', true); $this->load->database(); } function get_details() { $result1 = $this->db->query("select columnname1 tablename")->result(); $result2 = $this->db_2->query("select columnname2 tablename")->result(); }
i getting error because columnname2
exists in database2 table , not in database1 table.error: unknown column 'columnname2' in 'field list'
database.php
$db['database2']['hostname'] = 'localhost'; $db['database2']['username'] = 'root'; $db['database2']['password'] = ''; $db['database2']['database'] = 'database2'; $db['database2']['dbdriver'] = 'mysql'; $db['database2']['dbprefix'] = ''; $db['database2']['pconnect'] = true; $db['database2']['db_debug'] = true; $db['database2']['cache_on'] = false; $db['database2']['cachedir'] = ''; $db['database2']['char_set'] = 'utf8'; $db['database2']['dbcollat'] = 'utf8_general_ci'; $db['database2']['swap_pre'] = ''; $db['database2']['autoinit'] = true; $db['database2']['stricton'] = false; $active_group = 'default'; $active_record = true; $db['default']['hostname'] = 'localhost'; $db['default']['username'] = 'root'; $db['default']['password'] = ''; $db['default']['database'] = 'database1'; $db['default']['dbdriver'] = 'mysql'; $db['default']['dbprefix'] = ''; $db['default']['pconnect'] = true; $db['default']['db_debug'] = true; $db['default']['cache_on'] = false; $db['default']['cachedir'] = ''; $db['default']['char_set'] = 'utf8'; $db['default']['dbcollat'] = 'utf8_general_ci'; $db['default']['swap_pre'] = ''; $db['default']['autoinit'] = true; $db['default']['stricton'] = false;
update: if use following
function __construct() { parent::__construct(); $this->load->database(); $this->db_2 = $this->load->database('database2', true); }
database2 taken active ci , queries connected database 2 though $this->db->query();
used specify queries.
calling both database instances in constructor cause 1 override other. easiest way around split function , merge them together.
function __construct() { $this->load->database('default', true); } function merge_results() { $result_a = $this->get_result_a(); $result_b = $this->get_result_b(); return array_merge($result_a,$result_b); } function get_result_a() { return $this->db->query("select columnname1 tablename")->result(); } function get_result_b() { $other_db = $this->load->database('db2',true); return $other_db->query("select columnname2 tablename")->result(); }
Comments
Post a Comment