12

SCENARIO: I'm building a web application that uses ion_auth to manage all of the user/administrator information (uses MySQL database), and each user has their own database (MySQL as well) for core application purposes. I've autoloaded the database that I'm using for ion_auth in the application/config/database.php file within CodeIgniter. I am using standard MVC format (individual models pertaining to each database).

ISSUE: I'm needing to know how to use multiple databases at once within CodeIgniter easily and efficiently. Do I need to link the two database schemas together, or will CodeIgniter do that for me? Are there any resources out there that address this issue (I've had trouble trying to find one)?

1
  • 1
    How do you would like to use multiple databases? By configuration? By controller? Switching manually? Commented Sep 29, 2011 at 17:32

1 Answer 1

23

in your database config file add as many configuration groups as the numbers of your databases:

$db['a']['hostname'] = 'localhost';
$db['a']['username'] = 'user';
$db['a']['password'] = 'pw';
$db['a']['database'] = 'db1';
...

$db['b']['hostname'] = 'localhost';
$db['b']['username'] = 'user';
$db['b']['password'] = 'pw';
$db['b']['database'] = 'db2';
...

//set the default db
$active_group = 'a';

then on your model initialize a class variable:

private $db_b;

and, into the contructor, set it as follow

__construct()
{
   ...
   $this->db_b = $this->load->database('b', TRUE); 
}

now you are able to use the database b as usual:

$this->db_b->query('YOUR QUERY');

and obviously the default one as follow:

$this->db->query('YOUR QUERY');
Sign up to request clarification or add additional context in comments.

1 Comment

Make sure to set $db['default']['pconnect'] = FALSE;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.