Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DatabaseException extends Exception
- {
- const UNKNOWN = 0;
- const BAD_CONNECT = 1;
- public function __construct($message, $code = 0, Exception $previous = null)
- {
- parent::__construct($message, $code, $previous);
- }
- }
- class DatabaseHelper
- {
- private $conn = null;
- const DEFAULT_HOST = 'localhost';
- const DEFAULT_PORT = 5432;
- const DEFAULT_DATABASE = 'database';
- const DEFAULT_USER = 'user';
- const DEFAULT_PASSWORD = 'password';
- private $host;
- private $port;
- private $database;
- private $user;
- private $password;
- private $DSN;
- private static $gdbh = null;
- function __construct($host = DatabaseHelper::DEFAULT_HOST, $port = DatabaseHelper::DEFAULT_PORT,
- $database = DatabaseHelper::DEFAULT_DATABASE, $user = DatabaseHelper::DEFAULT_USER, $use_password = TRUE,
- $password = DatabaseHelper::DEFAULT_PASSWORD)
- {
- $this->host = $host;
- $this->port = $port;
- $this->database = $database;
- $this->user = $user;
- $this->password = $password;
- if ($use_password)
- {
- $this->DSN = sprintf("pgsql:host=%s;port=%d;dbname=%s;user=%s;password=%s",
- $this->host, $this->port, $this->database, $this->user, $this->password);
- }
- else
- {
- $this->DSN = sprintf("pgsql:host=%s;port=%d;dbname=%s;user=%s",
- $this->host, $this->port, $this->database, $this->user);
- }
- }
- function __destruct()
- {
- $this->close();
- }
- public function connect()
- {
- try
- {
- $this->conn = new PDO($this->DSN);
- }
- catch (PDOException $e)
- {
- $error_arr = $pstmt->errorInfo();
- $error_str = "Could not connect to server. "
- . "SQLSTATE code: " . $error_arr[0]
- . ", Driver code: " . $error_arr[1]
- . ", Message: " . $error_arr[2];
- throw new DatabaseException($error_str, DatabaseException::BAD_CONNECT, $e);
- }
- }
- public function close()
- {
- $this->conn = null;
- }
- public function getConnection()
- {
- if ($this->conn == null)
- {
- $this->connect();
- }
- return $this->conn;
- }
- public static function getInstance()
- {
- if (DatabaseHelper::$gdbh == null)
- {
- DatabaseHelper::$gdbh = new DatabaseHelper();
- }
- return DatabaseHelper::$gdbh;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement