Lvkz Lvkz - 1 year ago 118
PHP Question

Load database connection data dynamically in Codeigniter

I'm trying to accomplish the following functionality: I have a main connection to a database (inside application/config/database.php: db['default']), and that connections work, it retrieves data, I want to use that data to establish a new connection to a different DB.

Is that possible or I need to create an external PDO connection to handle it?

(I'm using Codeigniter 3.1.0)

Answer Source

With the help of Touheed Khan I was able to reach the solution of my problem, posting it here because I had to do some workaround of the suggested solution to make it work. The following is how my solution is working right now:


<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Controller extends CI_Controller {
 public $dynamicDB;

 public function __construct() {

 public function index() {
  //Somehow retrieve the following information from user.
  // End of retrieval information from user.

  $this->dynamicDB = array(
   'hostname' => $host,
   'username' => $user,
   'password' => $pass,
   'database' => $dbname,
   'dbdriver' => 'postgre',
   'dbprefix' => '',
   'pconnect' => FALSE,
   'db_debug' => TRUE,
   'port' => $port

  $result = $this->data_model->select($this->dynamicDB, 


<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Data_model extends CI_Model {
 function __construct(){

 public function returnQuery($query) {
  if ($query->num_rows() > 0) {
   return $query->result();
  } else {
   return array();

 public function select($dynamicDB, $id) {
  $dynamicDB = $this->load->database($dynamicDB, TRUE);

  $dynamicDB->where('id', $id);

  $query = $dynamicDB->get();
  return $this->returnQuery($query);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download