In general you only have 1 database configured in the file /application/config/database.php
Codeigniter and by default the configuration is called default
:
// Isto já existe
$db['default'] = array(
'dsn' => '',
'hostname' => '80.45.168.49',
'username' => 'steven.douglas',
'password' => 'hEo&73T#@wToh',
'database' => 'main_db',
'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
);
You will need to set up another one right after, and name it, for example, auxiliar
:
// Isto terá que ser adicionado
$db['auxiliar'] = array(
'dsn' => '',
'hostname' => '80.45.168.50',
'username' => 'john.eastwood',
'password' => 'cEsl#$tAnw4Mh',
'database' => 'another_bd',
'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
);
And looking at the My_model class, which is called that precisely because it is for you to customize it, you see that the configuration default
is associated with the variable $db
. Then you will have to create a variable like $db2
, or a name of your choice, for your auxiliar
, editing the file /application/core/MY_Model.php
:
class MY_Model extends CI_Model
{
protected $active_group;
protected $db2; // <------ ADICIONE
public function __construct() {
parent::__construct();
$this->connect();
}
public function __destruct() {
$this->db->close();
}
public function connect($active_group = 'default'){
$this->active_group = $active_group;
$db = $this->load->database($active_group, TRUE);
$this->db = $db;
// ADICIONE ISTO ABAIXO
$db2 = $this->load->database('auxiliar', TRUE);
$this->db2 = $db2;
}
}
Ready! Now you can use $this->db2
in their models:
$query = $this->db2->select('nome_pessoa, numero_cpf')->get('pessoas');
Hello C. Bohok, first thank you for the reply. Had thinking about this solution the problem is that this DB2 connection it changes as the user who is logged in, that is, if it is the user A1 for example he BD2 must connect in the BD1 database, if it is the user A2 the DB2 connection must connect in the DB2 database, and so on. It is this connection of DB2 that needs to be dynamic depending on the user who is connected in the system at that time, this your solution even works but it is not dynamic in the second database
– Jorge Ribeiro Junior