March 5, 2012

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!