0

Here is my scenario. A user will login to the system. Based on the username, I need to set the database in codeigniter configuration. I know that the line $this->load->database() in each model loads the default database. So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database?

Below is something that I am looking for:

if(username == 'foo'){
    $this->load->database('database_name');
}

An example of a model function that I have written is as follows:

public function check_valid_login($username, $password){
    $this->db->from('tbl_user_details');
    $this->db->where('email_address', $username);
    $this->db->where('password', md5($password));
    $query = $this->db->get();
    $rowcount = $query->num_rows();
    return $rowcount ;
}

On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?

Biju
  • 106
  • 1
  • 10

2 Answers2

0

I think I found a solution. This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user. The following logic is used for selecting the database dynamically. The below code is written in config/database.php

/*Dynamic database selection - begins*/
if(!empty($_SESSION['dynamic_db_username'])){
    $dynamic_db_username = $_SESSION['dynamic_db_username'];

    if($dynamic_db_username == 'sample@domain.com')
    {
        $db['default']['database'] = 'database_1';
    }
    elseif($dynamic_db_username == 'sample2@domain.com')
    {
        $db['default']['database'] = 'database_2';
    }
    else
    {
        $db['default']['database'] = 'database_1';
    }
}
else
{
    $db['default']['database'] = 'database_1';
}

/*End*/

Kindly review this strategy and please let me know if this is right.

Biju
  • 106
  • 1
  • 10
0

in the config folder there was a file named autoload.php open the file

find first this code below

  $autoload['libraries'] = array('');

you have to put "database" in the array , changed code will be like

  $autoload['libraries'] = array('database');

after that you can use your database anytime and anywhere without loading it manually .

Arif Sajal
  • 123
  • 2
  • 9
  • Thanks for the answer, but the requirement is that I need to be able to select a database based on particular condition dynamically. - Thanks. – Biju Nov 30 '16 at 07:23