是否可以在php函数中使用两个不同数据库中的两个表?

时间:2018-01-03 08:31:18

标签: php database class object pdo

我正在为我当前的项目使用两个数据库。我想在单个函数内的两个数据库上使用表。我使用类对象调用此函数,其构造函数连接单个数据库。如何一次连接多个数据库? 在此先感谢。

$DB1 = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME1,DB_USER1,DB_PASS1);//(host;dbname,dbuser,dbpass)
$DB1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DB1->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);//to avoid quote numeric arguments

$DB2 = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME2,DB_USER2,DB_PASS2);//(host;dbname,dbuser,dbpass)
$DB2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DB2->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);//to avoid quote numeric arguments

class Connect{
private $dbh;

//Database Connection
public function __construct($DB_con) {
    $this->dbh = $DB_con;
}

//function to select values from a table
public function select_rows($table,$fieldlist,$condition,$data) {
    $stmt = $this->dbh->prepare("SELECT $fieldlist FROM $table $condition");
    $stmt->execute($data);
    //$stmt->debugDumpParams(); 
    return $stmt;
}//end function

//function to update values in a table
public function update_rows($table,$fieldlist,$condition,$data) {
    $stmt = $this->dbh->prepare("UPDATE $table set $fieldlist $condition");
    $stmt->execute($data);
    return $stmt;
}//end function

//function to update values in a table
public function manage_tables($id1,$id2,$value1,$value2) {
    $cond_db1 = "WHERE ID=?";
    $data_db1 = array($id1);
    $pass_db1 = $this->select_rows('table_from_db1','*',$cond_db1,$data_db1);
    if($pass_db1->rowCount()>0)
    {
        //This section is not working as I called function using object of first db 
        $field_db2    =   "field1=?,field2=?";
        $cond_db2    =   " WHERE cID=? ";
        $data_db2     =   array($value1,$value2,$id2);
        $query_db2    =   $this->update_rows("table_from_db2",$field_db2,$cond_db2,$data_db2);
    }
}//end function

} //结束课

$obj1   = new Connect($DB1);
$obj2   = new Connect($DB2);

$func   =   $obj1->manage_tables($id1,$id2,$value1,$value2);

0 个答案:

没有答案