I'm fairly new to PHP; however I think I have a good grasp on it, but I'm having an issue understanding why I'm not able to access a second version of a connect to DB class I have.
I connect globally to the first one in a config script.
$db = new db(array('login info'));
I access it in my controller using the following.
public $db;
public function __construct(){
$this->db = $GLOBALS['db'];
}
Then inside my controller I have a function where I create a new instance of this to connect to a different DB.
$ordersDB = new db(array('login info'));
Now I would like to access each database separately using something like
$this->db->select("SELECT * FROM ada Yada
and
$ordersDB->select("SELECT * FROM Yada Yada
However both are still accessing the first db. I know this because I am getting a table does not exist error when executing the second one and it tells me what db its querying. However a var_export of them shows they are infact different! Am I completely misunderstanding how classes work or can I only have one DB open at a time? Thanks for any help.
Edit: Is this what you are looking for?
$db = new db(array(connect info));
$controller = new controller();
$controller->connectToSecondDB();
class db {
public $dbHost;
public $dbUser;
public $dbName;
public $dbPassword;
public function __construct() {
$arguments = func_get_args();
if(!empty($arguments)){
foreach($arguments[0] as $key => $property){
if(property_exists($this, $key)){
$this->{$key} = $property;
}
}
}
}
public function connect() {
if(!isset(self::$connection)) {
self::$connection = new mysqli($this->dbHost, $this->dbUser, $this->dbPassword, $this->dbName);
}
}
class controller {
public $db;
public function __construct(){
$this->db = $GLOBALS['db'];
}
public function connectToSecondDB(){
$ordersDB = new db(array(connect info));
$ordersDB->select("SELECT * FROM `customer` WHERE email = 'email@address.com' LIMIT 1")
$this->db->query("SQL");
}
}
EDIT Select Query Function
private function _sel($table, $where="", $order_by="", $limit="", $group_by="",$database = NULL){
if($database === NULL) { $database = $this->db; }
if($limit == 1){ $single = true; }else{ $single = false; }
//if( is_array($where) ){ $this->_buildWhere(); }
$where = (strlen($where) > 0) ? "WHERE $where " : $where;
$group_by = (strlen($group_by) > 0) ? "GROUP BY $group_by " : $group_by;
$order_by = (strlen($order_by) > 0) ? "ORDER BY $order_by " : $order_by;
$limit = (strlen($limit) > 0) ? "LIMIT $limit " : $limit ;
$sql = "SELECT *
FROM `$table`
$where
$group_by
$order_by
$limit";
// Debug
//if(INCLUDE_CHECK){ echo "<HR>".$sql."<HR>"; }
$results = $database->select($sql);
if($single && count($results) > 0 ){
return($results[0]);
}else{
return($results);
}
}