I am building a web app with CI 3, I have to use 2 different database connections for certain requirement. I have loaded the configuration to the database.php file and I can of course connect to them using the built in classes.
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'primary',
'dbdriver' => 'mysqli'
);
$db['customer'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root_1',
'password' => 'root_1',
'database' => 'secondary',
'dbdriver' => 'mysqli'
);
I am using a MY_Model from here. So I extend them as follows..
class Table extends MY_Model
{
public function __construct()
{
parent::__construct();
$this->_database = $this->load->database('customer', TRUE);
}
public function create_table()
{
return $this->_database->query("CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)");
}
}
But I need to use dbForge to create tables. But only 'default' connection is used with the dbForge class. Codeigniter dbForge documentation doesn't give a way to load different db connections to the dbForge. Anyone know how to tackle the issue in an elegant way?
After little bit research I found the right way to do it.
$this->load->dbForge()
can actually take a parameter, If we pass a database object it will use that connection to perform the operation.
In addition, we can pass a second argument and get a separate object as well.
$this->dbForgeSecondary = $this->load->dbforge($this->_database, TRUE);
Easy & Pretty Cool.