I have seen this topic and tried to implement that way and unfortunatelly isn't working.
I need to dynamically connect to a database with CodeIgniter. This database cannot be a constant variable in the file application/config/databases.php. I have tried two different ways of connecting to a different database:
The first one is by model - with third parameter as documentation refers.
class users extends CI_Controller
{
public function __construct()
{
parent::_construct();
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['database'] = 'clockin_AlKj';
$config['dbdriver'] = 'mysqli';
$config['dbprefix'] = '';
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$this->load->model('company_model', '', $config);
$this->company = $this->company_model->get();
}
}
This throws the error:
Error Number: 1146
Table 'clockin_admin.company' doesn't exist
SELECT * FROM (
company)Filename: C:\xampp\htdocs\clockin\system\database\DB_driver.php
The second way is to connect by using database.
class users extends CI_Controller
{
public function __construct()
{
parent::_construct();
$this->load->model('company_model');
$this->company = $this->company_model->get();
}
}
class Company_model extends CI_model
{
private $otherDb;
public function __construct()
{
parent::__construct();
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['database'] = 'clockin_AlKj';
$config['dbdriver'] = 'mysqli';
$config['dbprefix'] = '';
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$this->otherDb = $this->load->database($config);
}
public function get()
{
$this->otherDb->get('company')->row();
}
}
This throws the error:
Fatal error: Call to a member function get() on a non-object in C:\xampp\htdocs\clockin\application\models\company_model.php on line 45
Which refers to the line $this->otherDb->get('company')->row();
The problem is that if I verify if the connection was established it also returns error.
if($this->load->database($config) === FALSE)
echo 'Yes, I could not connect..';
Finally, my configuration of file database.php is the following:
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'clockin_admin';
$db['default']['dbdriver'] = 'mysqli';
$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;