CodeIgniter Connect Blog With Different Databases

If a single database is having too much load and if you want to move the blog section to another database then you can use the different database for blog.


In CodeIgniter, you need to set different database connection setting for this and call database as per requirement.

  1. Database Configuration Setting

Database connections details defined in application/config/database.php file.

Edit application/config/database.php file.

Define your site main database details as default.

Now for defining another database, create copy of $db[‘default’].
Create blog database array same as default database array with blog database like $db[‘blog’]

Sample Code:

$active_group = 'default';
$query_builder = TRUE;

$db = array();

// main database setting
$db['default']['dsn'] = '';
$db['default']['hostname'] = 'main database hostname';
$db['default']['username'] = 'main database username';
$db['default']['password'] = 'main database password';
$db['default']['database'] = 'main database name';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['encrypt'] = FALSE;
$db['default']['compress'] = FALSE;
$db['default']['stricton'] = FALSE;
$db['default']['save_queries'] = TRUE;
// blog database setting
$db['blog']['dsn'] = '';
$db['blog']['hostname'] = 'blog database hostname';
$db['blog']['username'] = 'blog database username';
$db['blog']['password'] = 'blog database password';
$db['blog']['database'] = 'blog database name';
$db['blog']['dbdriver'] = 'mysqli';
$db['blog']['dbprefix'] = '';
$db['blog']['pconnect'] = FALSE;
$db['blog']['cache_on'] = FALSE;
$db['blog']['cachedir'] = '';
$db['blog']['char_set'] = 'utf8';
$db['blog']['dbcollat'] = 'utf8_general_ci';
$db['blog']['swap_pre'] = '';
$db['blog']['encrypt'] = FALSE;
$db['blog']['compress'] = FALSE;
$db['blog']['stricton'] = FALSE;
$db['blog']['save_queries'] = TRUE;

2. Call Blog Database

We need to define blog_model, blog database like this way:

$db_blog = $this->load->database('blog', TRUE);

Now, use your blog database in blog_model functions and call in blog controller:

Sample Code:

$db_blog->select('*');
$records = $db2->get('tbl_blogs');
$result = $records->result_array();

Leave a Reply