【发布时间】:2011-07-23 14:57:50
【问题描述】:
我想在 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;
}
}
?>
我在浏览器中收到消息“连接已重置”,怎么了?
【问题讨论】:
-
您能否提供错误消息或说明究竟是什么失败了?我目前的猜测是,
DatabaseConnection类中没有名为query的方法。 -
@vstm :不,什么都没有出现,什么都没有。你以前有过 PDO 吗?
-
如果没有显示任何内容,则最终没有错误,并且您的脚本不会产生任何输出。另一方面,PHP 可能会抑制错误消息。如果
display_errors是on 并且error_reporting设置为E_ALL | E_STRICT,请检查您的php.ini。如果display_errors已打开并且仍然没有输出,则应添加echo "hello world";以检查脚本是否正常运行。
标签: php postgresql pdo