-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.php
executable file
·124 lines (99 loc) · 3.2 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
class QueryParameters
{
private $parms = array();
public function addParameter($parameterName, $parameterValue)
{
$this->parms[$parameterName] = $parameterValue;
}
public function clear()
{
unset($this->parms);
}
public function getParameterValue($parameterName)
{
return $this->parms[$parameterName];
}
public function getParameterNames()
{
return array_keys($this->parms);
}
}
class Database
{
public $MaintenanceMode;
protected $dbConnection = null;
private function bindParameters($stmt, $parms)
{
if ($parms != null)
{
//print "doing parameter binding...\n";
foreach($parms->getParameterNames() as $parameterName)
{
$stmt->bindValue($parameterName, $parms->getParameterValue($parameterName));
//print "binding parameter $parameterName with " . $parms->getParameterValue($parameterName) . "\n";
}
}
}
public function execute($query, QueryParameters $parms = null)
{
if ($this->dbConnection == null)
throw new Exception("Cannot execute a query, no open connection.");
$stmt = $this->dbConnection->prepare($query);
$this->bindParameters($stmt, $parms);
if ($this->MaintenanceMode == false)
$stmt->execute();
return $stmt;
}
public function select($query, $parms = array())
{
if ($this->dbConnection == null)
throw new Exception("Cannot execute a query, no open connection.");
$stmt = $this->dbConnection->prepare($query);
$this->bindParameters($stmt, $parms);
if ($this->MaintenanceMode == false)
$stmt->execute();
$result = null;
while ($row = $stmt->fetch())
{
if ($result == null)
$result = array();
$result[] = $row;
}
return $result;
}
public function __construct(
$host,
$database,
$user,
$pass,
$maintMode = false
)
{
$this->initialize($host, $database, $user, $pass);
$this->maintenanceMode = $maintMode;
}
public function __destruct()
{
$this->dbConnection = null;
}
private function initialize($host, $database, $user, $pass)
{
if ($this->dbConnection != null)
{
throw new Exception("Database connection is already open.");
}
$cfg['host'] = $host;
$cfg['dbase'] = $database;
$cfg['user'] = $user;
$cfg['pass'] = $pass;
$conn = "mysql:host={$cfg['host']};dbname={$cfg['dbase']}";
$this->dbConnection = new PDO($conn, $cfg['user'], $cfg['pass']);
/*
catch (PDOException $e) {
header(':', true, 503);
printf("<div id=\"fail_connect\">\n <error details=\"%s\" />\n</div>\n", $e->getMessage());
}
*/
}
}