title: Change Database connection at runtime in Codeigniter
body: <p>I want to connect to a different database based on the sub domain, Currently I've this code, but it not looking a decent solution to the problem. Please guide in right direction what is the best way to achieve this in code igniter. </p>
  
  <pre><code>class DBConnection extends CI_Model
  {
      public function __construct()
      {
          parent::__construct();
      }
  
      public function dbConfig(){
  
          $efg="";
          $data = explode('.',$_SERVER['SERVER_NAME']);
          if (!empty($data[0])) {
              $efg = $data[0];
          }
  
          $sql="SELECT DbUsername,DbName,DbPassword FROM abc WHERE efg=?";
          $d_result=$this-&gt;db-&gt;query($sql,array($efg))-&gt;result_array();
  
          $this-&gt;db-&gt;close();
  
          $config['hostname'] = "localhost";
          $config['username'] = $d_result[0]["DbUsername"];
          $config['password'] = $d_result[0]["DbPassword"];
          $config['database'] = $d_result[0]["DbName"];
          $config['dbdriver'] = "mysql";
          $config['dbprefix'] = "";
          $config['pconnect'] = FALSE;
          $config['db_debug'] = TRUE;
          $config['cache_on'] = FALSE;
          $config['cachedir'] = "";
          $config['char_set'] = "utf8";
          $config['dbcollat'] = "utf8_general_ci";
          return $config;
      }
  } 
  </code></pre>
  
  <p>Then in User model class, I've something like this, which is on each &amp; every request doing all the above processing again. I want the switch will take place in the start and further queries will push towards selected database.</p>
  
  <pre><code>class User extends CI_Model
  {
      private $clientDB;
  
      public function __construct()
      {
          parent::__construct();
          $db=new DBConnection();
          $this-&gt;clientDB=$this-&gt;load-&gt;database($db-&gt;dbConfig(),TRUE);
      }
  
      public function isUserExists($username,$password)
      {
          $sql="SELECT uid FROM `aaa` WHERE `uname`=? AND `upwd`=?";
          $d_result=$this-&gt;clientDB-&gt;query($sql,array($username,$password));
          return $d_result;
      }
  } 
  </code></pre>