Php – How to load another database using CodeIgniter

codeigniterPHP

I have a CodeIgniter and some Mysql database. But know I want to set the another database for working, and after some actions do disable it. For example, I have function make_some_actions_with_db(), and now I need to have something like that:

public function action()
{
//load db
make_some_actions_with_db();
//disable db
}

So, now I need to know how I can set the new default db and how I can set another (first) db. Thank you.

UPDATED:
It doesn't work:

   public function update_record_insert_test()
    {
        if ($this->facebook->getUser())
        {
            $another_db_settings['hostname'] = 'localhost';
            $another_db_settings['username'] = 'root';
            $another_db_settings['password'] = '';
            $another_db_settings['database'] = 'name';
            $another_db_settings['dbdriver'] = "mysql";
            $another_db_settings['dbprefix'] = "";
            $another_db_settings['pconnect'] = TRUE;
            $another_db_settings['db_debug'] = TRUE;
            $another_db_settings['cache_on'] = FALSE;
            $another_db_settings['cachedir'] = "";
            $another_db_settings['char_set'] = "utf8";
            $another_db_settings['dbcollat'] = "utf8_general_ci";
            $this->load->database($another_db_settings);

            $_POST['id']='AccountPagesView.a_book/1000';
            $_POST['value']='test';
            $_POST['old_value']='not';
            $welcome=new Welcome();
            $welcome->update_record();
        }
        else
        {
            $url=$this->facebook->getLoginUrl(array('next' => base_url().'update_record_insert_test'));
            redirect($url);
        }
    }

Best Answer

In your config/database.php your database is configured to the 'default' group, like so:

$db['default']['hostname'] = 'host';
$db['default']['username'] = 'username';
$db['default']['password'] = 'password';
$db['default']['database'] = 'database';

This allows you to specify other groups like this:

$db['second']['hostname'] = 'host';
$db['second']['username'] = 'username';
$db['second']['password'] = 'password';
$db['second']['database'] = 'database';

$db['third']['hostname'] = 'host';
$db['third']['username'] = 'username';
$db['third']['password'] = 'password';
$db['third']['database'] = 'database';

You can then connect to another database by using:

$defaultDB = $this->load->database('default', TRUE);
$secondDB = $this->load->database('second', TRUE);

By passing true as the second value, it will return the database object, allowing you to safely use the same methods for each database, like so:

$default->get('table');
$second->get('different_table');