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.
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->db->query($sql,array($efg))->result_array();
$this->db->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;
}
}
Then in User model class, I've something like this, which is on each & 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.
class User extends CI_Model
{
private $clientDB;
public function __construct()
{
parent::__construct();
$db=new DBConnection();
$this->clientDB=$this->load->database($db->dbConfig(),TRUE);
}
public function isUserExists($username,$password)
{
$sql="SELECT uid FROM `aaa` WHERE `uname`=? AND `upwd`=?";
$d_result=$this->clientDB->query($sql,array($username,$password));
return $d_result;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…