Where do I put database config values in Codeigniter?
Question by MotiveKyle
I am trying to connect to a different database than what is in my database config file.
I’ve been able to do this with the following in my model:
$wp['hostname'] = "localhost";
$wp['username'] = "root";
$wp['password'] = "";
$wp['database'] = "transfer";
$wp['dbdriver'] = "mysql";
$wp['dbprefix'] = "";
$wp['pconnect'] = FALSE;
$wp['db_debug'] = TRUE;
$wp['cache_on'] = FALSE;
$wp['cachedir'] = "";
$wp['char_set'] = "utf8";
$wp['dbcollat'] = "utf8_general_ci";
$wpDB = $this->load->database($wp, TRUE);
and then running queries like so: $query = $wpDB->get();
I can only get it to work when the config values are in the model itself (so there would be a lot of duplication). I’ve tried putting the config array in the constructor, but I get an error that it can’t find it.
Where can I put the config array so I don’t have to duplicate it and that’s available throughout the model?
Answer by Wesley Murch
Database configuration usually goes in config/database.php
. You can configure multiple database connections and store them with different group names:
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'host1';
$db['default']['username'] = 'user1';
$db['default']['password'] = '******';
$db['default']['database'] = 'my_db';
$db['other']['hostname'] = 'host2';
$db['other']['username'] = 'user2';
$db['other']['password'] = '******';
$db['other']['database'] = 'my_other_db;
The $active_group
refers to the default group when the database class is loaded. To connect to another group in your model, you can use this in the model’s __construct
method:
$this->db = $this->load->database('other', TRUE);
While this doesn’t play nicely with the more flexible $this->load->model('model_name', 'alias', $config)
approach, it might be easier.
More info: http://codeigniter.com/user_guide/database/connecting.html
Answer by Starx
Since your config data appears to be database related, store them in
system/application/config/database.php