PHP PDO Connection
I want create a connection class for database connection using PDO in PHP
开发者_运维百科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');
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 ?
That won't work. You either need to create a method that calls query
in PDO:
class DatabaseConnection {
// ...
public function query($sql) {
return $this->DBH->query($sql);
}
// ...
}
or extend 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?
class User {
private $connection;
public function __construct ($connection) {
$this->connection = $connection;
}
public function getUser() {
$STH = $this->connection->query('SELECT * from User');
}
}
精彩评论