Reputation: 625
I'm using codeigniter and the project i'm working on has to be in two languages.
The only thing i can't figure out is how to select a different database in codeigniter when a session variable is set to a certain value.
example:
if the session variable 'language' is set to 'EN' i want it to select the DB: "databasename_EN"
in all other cases select DB: "databasename_EN"
The only thing i found was that you can do $this->db->load('bla'); but this means you have to add a DB-load in every model and you have to disable autoload 'database'.
Upvotes: 2
Views: 1242
Reputation: 1057
A variation of Phil Sturgeaon answer:
$active_group = LANG; // switch the DB based on the LANG constant
$db['EN']['hostname'] = "localhost";
$db['EN']['username'] = "root";
$db['EN']['password'] = "";
$db['EN']['database'] = "databasename_EN";
// etc
$db['FR']['hostname'] = "localhost";
$db['FR']['username'] = "root";
$db['FR']['password'] = "";
$db['FR']['database'] = "database_FR";
//etc
Upvotes: 3
Reputation: 30766
For the best result I would create a pre_system hook that checks whether a $_SESSION['lang'] variable exists and if it does set a constant:
define('LANG', isset($_SESSION['lang']) ? $_SESSION['lang'] : 'EN');
Then in your database config file do this:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_".LANG;
$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";
Should do the trick with minimum fuss.
Upvotes: 4
Reputation: 1648
i guess you could create a MyModel class extending Model and handling this gymnastic. than all you'd need to do is use MyModel as the parent class of your models.
Upvotes: 1