-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.php
81 lines (63 loc) · 1.92 KB
/
database.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
if (!defined('UNDER_INDEX')) {
header('Location: /');
}
class Database {
private $connection;
public function connect($host, $port, $username, $password, $dbname) {
if ($this->isConnected()) {
return true;
}
$dsn = "pgsql:host=$host;port=$port;dbname=$dbname";
try {
$this->connection = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
throw new Exception('Connection failed ('.$e->getMessage().')');
}
return true;
}
public function isConnected() {
return isset($this->connection);
}
public function beginTransaction() {
if (!$this->isConnected()) {
return false;
}
return $this->connection->beginTransaction();
}
public function commit() {
if (!$this->isConnected()) {
return false;
}
return $this->connection->commit();
}
public function rollback() {
if (!$this->isConnected()) {
return false;
}
return $this->connection->rollback();
}
public function execute($sql, $parameters=array()) {
if (!$this->isConnected()) {
return false;
}
$statement = $this->connection->prepare($sql);
foreach ($parameters as $key => $value) {
$statement->bindValue(":$key", $value);
}
if ($statement->execute()) {
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
return $result;
} else {
$error = $statement->errorInfo();
$statement->closeCursor();
$backtrace = debug_backtrace();
throw new Exception($error[2].', file: '.$backtrace[0]['file'].' on line '.$backtrace[0]['line'], E_USER_ERROR);
}
}
public function disconect() {
$this->connection = null;
}
}
?>