我正在使用面向对象的Php。为了连接同一主机中的两个数据库,我正在使用这样的代码
<?php
class ConOs{
var $dbhost1;
var $dbuser1;
var $dbpass1;
var $dbhost2;
var $dbuser2;
var $dbpass2;
function __construct() {
}
function connect(){
$this->dbhost1="localhost";
$this->dbuser1="user1";
$this->dbpass1="db1";
$this->dbhost2="localhost";
$this->dbuser2="user2";
$this->dbpass2="db2";
$conn1 = mysql_connect($this->dbhost1, $this->dbuser1, $this->dbpass1);
if(! $conn1 ){die('Could not connect: ' . mysql_error());}
mysql_select_db("db1",$conn1);
$conn2 = mysql_connect($this->dbhost2, $this->dbuser2, $this->dbpass2, True);
if(! $conn2 ){die('Could not connect: ' . mysql_error());}
mysql_select_db("db2", $conn2);
mysql_error();
}
}
?>
但是$ conn1总是拒绝。只有$ conn2有效。如果我先把$ conn2放进去,那么只有$ conn1可以工作。如何连接数据库db1和amp; db2?
答案 0 :(得分:0)
我亲爱的停止使用mysql_ *函数:使用PDO:
class sujet{
private $id;
public function connect(){
try {
$bdd = new PDO('mysql:host=localhost;dbname=dev_bdd', 'root', '');
}catch(Exception $e){
die('Failed'. $e->getMessage());
}
return $bdd;
}
public function connect2(){
try {
$bdd = new PDO('mysql:host=localhost;dbname=teamd2', 'root', '');
}catch(Exception $e){
die('Failed'. $e->getMessage());
}
return $bdd;
}
public function __construct(){}
public function recherche($search){
$resultats = array();
$req = $this->connect2()->prepare('SELECT * FROM sujets WHERE libelle like :search ');
$req->execute(array(
'search' => '%'.$search.'%',
));
while($resultat = $req->fetch()){
array_push($resultats,$resultat);
}
print_r($resultats);
return $resultats;
}
private function queryMatiere(int $id){
$requete = $this->connect()->query("SELECT libelle FROM matieres where id=$id");
$data = $requete->fetch();
return $data['libelle'];
}
}