postgresql PHP PDO 连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6801202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP PDO Connection
提问by Ahmad
I want create a connection class for database connection using PDO in PHP
我想在 PHP 中使用 PDO 为数据库连接创建一个连接类
here is my code :
这是我的代码:
<?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;
}
}
?>
For query in PDO i must use $DBH->query('SELECT * from user');
对于 PDO 中的查询,我必须使用 $DBH->query('SELECT * from user');
but how if i user my connection class in other class ?
但是如果我在其他类中使用我的连接类呢?
example
例子
<?php
include "DatabaseConnection.php";
class User {
private $connection;
public function getUser() {
$this->connection = new DatabaseConnection();
$STH = $this->connection->query('SELECT * from User');
}
}
?>
But it's not work.
但它不起作用。
Any body can help me ? Thanks :)
任何机构都可以帮助我?谢谢 :)
UPDATE:
更新:
After follow Jonah suggest,
在跟随约拿的建议之后,
<?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;
}
}
?>
i got message "The connection was reset" in browser, whats wrong ?
我在浏览器中收到消息“连接已重置”,怎么了?
回答by Jonah
That won't work. You either need to create a method that calls query
in PDO:
那行不通。您要么需要创建一个query
在 PDO中调用的方法:
class DatabaseConnection {
// ...
public function query($sql) {
return $this->DBH->query($sql);
}
// ...
}
or extend PDO.
或扩展 PDO。
class DatabaseConnection extends PDO {
// ...
}
Update:On the other hand, there is very little point in wrapping the PDO class at all. Why not just create a PDO object directly?
更新:另一方面,包装 PDO 类根本没有什么意义。为什么不直接创建一个 PDO 对象呢?
回答by KingCrunch
class User {
private $connection;
public function __construct ($connection) {
$this->connection = $connection;
}
public function getUser() {
$STH = $this->connection->query('SELECT * from User');
}
}