我剛剛開始學習面向對象編程的概念,並將一個類連接到數據庫,選擇數據庫並關閉數據庫連接。到目前爲止,除了關閉與數據庫的連接外,一切似乎都行得通。OOP數據庫連接/斷開類
class Database {
private $host, $username, $password;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
}
public function connectdb(){
mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
echo 'successfully connected to database<br />';
}
public function select($database){
mysql_select_db($database)
OR die("There was a problem selecting the database.");
echo 'successfully selected database<br />';
}
public function disconnectdb(){
mysql_close($this->connectdb())
OR die("There was a problem disconnecting from the database.");
}
}
$database = new database('localhost', 'root', 'usbw');
$database->connectdb();
$database->select('msm');
$database->disconnectdb();
當我試圖從數據庫中,我得到了以下錯誤消息斷開:
Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53
我猜它並不像放置connectdb方法mysql_close的括號內爲簡單功能,但無法找到正確的方法來做到這一點。
感謝
順便說一句,如果你打算這樣做,你可能還需要爲類中的數據庫連接保留一個真正的資源。 – 2012-03-10 23:23:38
當你說在類中保持數據庫連接的真實來源時,你是什麼意思? – crm 2012-03-10 23:35:42
@crm:添加一個私有成員並將其存儲在那裏,如'$ this-> connection'。 – hakre 2012-03-10 23:40:01