Codeigniter dynamic database connection Codeigniter dynamic database connection codeigniter codeigniter

Codeigniter dynamic database connection


You should provide the all database information in application/config/database.php´

Normally, you would set the default database group, like so:

$db['default']['hostname'] = "localhost";$db['default']['username'] = "root";$db['default']['password'] = "";$db['default']['database'] = "database_name";$db['default']['dbdriver'] = "mysql";$db['default']['dbprefix'] = "";$db['default']['pconnect'] = TRUE;$db['default']['db_debug'] = FALSE;$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;

Notice that the login information and settings are provided in the array named $db['default'].

You can then add another database in a new array - let's call it 'anotherdb'.

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

Now if you want to use the second database, just go

$DB_another = $this->load->database('anotherdb', TRUE); 

and then, instead of $this->db->foo() , you will you $DB_another->foo()

and you can extend this to multiple groups like this

 $DB2 = $this->load->database('anotherdb1', TRUE);  $DB3 = $this->load->database('anotherdb2', TRUE); 

For details have a look here:http://ellislab.com/codeigniter/user-guide/database/connecting.html


$this->load->database($connectdb);

The problem is here, you load this variable in the constructor that you set in your index function.

__constructor() is fired before index() so i guess you should do something like this:

class Main extends CI_Controller {private $connectdb;function __construct(){    parent::__construct();    /* Standard Libraries of codeigniter are required */    $this->_setConnectdb();    $this->load->database($this->connectdb);    $this->load->helper('url');    $this->load->library('grocery_CRUD');}public function _setConnectdb(){if ( $_POST["username"] == "root" ) {    $this->connectdb = "default";}if ( $_POST["username"] == "user1" ) {    $this->connectdb = "default1";}if ( $_POST["username"] == "user2" ) {    $this->connectdb = "default2";}