[英]PHP PDO Connection
我想在PHP中使用PDO創建數據庫連接的連接類
這是我的代碼:
<?php
class DatabaseConnection {
private $dbname = "db_01";
private $host = "localhost";
private $user = "xxx";
private $password = "xxxxxx";
private $port = 5432;
private $DBH;
public function __construct() {
try {
$this->DBH = new PDO("pgsql:host=$this->host;port=$this->port;dbname=$this->dbname;user=$this->user;password=$this->password");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function disconnect() {
$this->DBH = null;
}
}
?>
對於PDO中的查詢,我必須使用$ DBH-> query('SELECT * from user');
但是,如果我在其他課程中使用我的連接課程,該怎么辦?
例
<?php
include "DatabaseConnection.php";
class User {
private $connection;
public function getUser() {
$this->connection = new DatabaseConnection();
$STH = $this->connection->query('SELECT * from User');
}
}
?>
但這是行不通的。
有誰能幫助我? 謝謝 :)
更新 :
按照約拿的建議,
<?php
class DatabaseConnection extends PDO {
private $dbname = "db_01";
private $host = "localhost";
private $user = "xxx";
private $password = "xxxxxxxxx";
private $port = 5432;
public function __construct() {
try {
parent::__construct("pgsql:host=$this->host;port=$this->port;dbname=$this->dbname;user=$this->user;password=$this->password");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function disconnect() {
$this = null;
}
}
?>
我在瀏覽器中收到消息“連接已重置”,怎么了?
那行不通。 您要么需要創建一種在PDO中調用query
的方法:
class DatabaseConnection {
// ...
public function query($sql) {
return $this->DBH->query($sql);
}
// ...
}
或擴展PDO。
class DatabaseConnection extends PDO {
// ...
}
更新:另一方面,包裝PDO類根本沒有意義。 為什么不直接創建PDO對象呢?
class User {
private $connection;
public function __construct ($connection) {
$this->connection = $connection;
}
public function getUser() {
$STH = $this->connection->query('SELECT * from User');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.