One is the default and the other one is the second DB which I need only in few controllers to maintain the orders coming through the system. Here is the code, my database.php
file is as follows:
Here is my configuration:
`$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'carbiz',
'dbdriver' => 'mysqli',
'dbprefix' => 'web_',
'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['abcd'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'sale2',
'dbdriver' => 'mysqli',
'dbprefix' => 'web_',
'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
);`
Here is My Controller
public function __construct()
{
parent::__construct();
$this->load->model('admin_model');
$this->otherdb = $this->load->database('abcd', TRUE);`
}
Now In One Function in same controller which uses the second db
function add_scondary()
{
$val=$this->otherdb->select('title')->get('products');
print_r("here");
print_r($val);
}
const CI_VERSION = '3.1.7';
Hope this will help You :
First you have to define a public
or private
variable $otherdb
like this
public $otherdb;
public function __construct()
{
parent::__construct();
$this->otherdb = $this->load->database('abcd', TRUE);
}
function add_scondary()
{
$data = $this->otherdb->get('products')->result();
print_r(data);
}
The better way to use different database with same connection :
You don’t need to create separate database configurations if you only need to use a different database on the same connection. You can switch to a different database when you need to, like this:
$this->db->db_select('sale2');
$data['abcd'] = $this->db->get('products')->result();