Search code examples
phpdatabase-connectioncodeigniter-2

Switch databases in CodeIgniter


Sorry if this is a real newbie question (also a php newbie), but I can't figure it out from the docs:

I want to be able to use a default database, if I don't speficy anything else, and that works fine using $this->db with the following configuration:

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'root';
$db['default']['database'] = 'ion_auth';
$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;

$db['visitorsDB']['hostname'] = 'localhost';
$db['visitorsDB']['username'] = 'root';
$db['visitorsDB']['password'] = 'root';
$db['visitorsDB']['database'] = 'visitorsDB';
$db['visitorsDB']['dbdriver'] = 'mysql';
$db['visitorsDB']['dbprefix'] = '';
$db['visitorsDB']['pconnect'] = TRUE;
$db['visitorsDB']['db_debug'] = TRUE;
$db['visitorsDB']['cache_on'] = FALSE;
$db['visitorsDB']['cachedir'] = '';
$db['visitorsDB']['char_set'] = 'utf8';
$db['visitorsDB']['dbcollat'] = 'utf8_general_ci';
$db['visitorsDB']['swap_pre'] = '';
$db['visitorsDB']['autoinit'] = TRUE;
$db['visitorsDB']['stricton'] = FALSE;

But then I want to use the second database in one of my models, so I tried this:

function __contruct() {
      parent::__construct();
       $this->db =  $this->load->database('visitorsDB', TRUE);
   }

   public function getAllVisitors($paramArr) {
       //$this->db =  $this->load->database('visitorsDB', TRUE);

But that doesn't work. Only if I uncomment the last line so that I load the database in the method itself will it work. I don't understand why. I also tried declaring a new class variable at the beginning of the class - private $myDB; - and then instantiating it in the constructor - $myDB = $this->load->database('visitorsDB', TRUE);

But that didn't work either. So how can I switch database for the entire model?


Solution

  • I wouldn't recommend selecting a second database by overwriting $this->db. Just add a property for your other database in the model you need it and access it through that. In your model do this:

    private $myDB;
    
    function __construct() {
        parent::__construct();
        $this->myDB = $this->load->database('visitorsDB', TRUE);
    }
    
    function getAllVisitors() {
        return $this->myDB->someMethod(); // Or use active record, etc...
    }
    

    I know in your question you said that you did something similar but I'm not sure if you did it correctly. This would be the correct way of doing so and I don't see why it wouldn't work if it was done this way.