Multiple databases with one application in php and codeigniter

I developed a site in php codeigniter with the idea of ​​using one physical instance of the code.

Here the logic I would like to be is on the login page, the company will be selected to be internally linked to the database name. I want to know how to update the active_group variable according to the company ID selected by the user during login.

Is there any way to do this.

+2


a source to share


1 answer


Will you need to have a master database to authenticate the user and store information anyway? Therefore, you need to manage two connections. You can set default connection and then set 2nd config in MY_Controller .

This MY_Controller will handle the user detection (from the auto-loaded database class and whatever model / lib / auth system is in use), then it will of course get the database name from the user, but can be attached.

Then you can use code like this to set the 2nd bit:



class  MY_Controller extends Controller
{
    function MY_Controller ()  {

        parent::Controller();

        $this->user = $this->auth->get_user($this->input->post('username'), $this->input->post('password'));
        $this->company = $this->company->get($this->input->post('company_id'));

        $config['hostname'] = "localhost";
        $config['username'] = "myusername";
        $config['password'] = "mypassword";
        $config['database'] = $this->company->database;
        $config['dbdriver'] = "mysql";
        $config['dbprefix'] = "";
        $config['pconnect'] = FALSE;
        $config['db_debug'] = TRUE;
        $config['cache_on'] = FALSE;
        $config['cachedir'] = "";
        $config['char_set'] = "utf8";
        $config['dbcollat'] = "utf8_general_ci";

        $this->company_db = $this->load->database($config, TRUE);
    }

}

      

Then you can interact with $ this-> company_db as well as $ this-> db. The first one would be for the db to interact with their database, the last one to interact with the default main connection.

+2


a source







All Articles