/
mysql.php
321 lines (250 loc) · 8.89 KB
/
mysql.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<?php
/* MYSQL class
Depends on having the debug() and getmicrotime() functions available elsewhere to output debugging info.
Somewhere (probably in includes/easyparliament/init.php) there should be something like:
Class ParlDB extends MySQL {
function ParlDB() {
$this->init (OPTION_TWFY_DB_HOST, OPTION_TWFY_DB_USER, OPTION_TWFY_DB_PASS, OPTION_TWFY_DB_NAME);
}
}
Then, when you need to do queries, you do:
$db = new ParlDB;
$q = $db->query("SELECT haddock FROM fish");
$q is then a MySQLQuery object.
If other databases are needed, we just need to create a class for each, each one
extending MySQL.
Call $db->display_total_duration() at the end of a page to send total query time to debug().
(n is 0-based below...)
After a SELECT
==============
If successful:
$q->success() returns true.
$q->rows() returns the number of rows selected
$q->row(n) returns an array of the nth row, with the keys being column names.
$q->field(n,col) returns the contents of the "col" column in the nth row.
$q->insert_id() returns NULL.
$q->affected_rows() returns NULL.
If 0 rows selected:
$q->success() returns true.
$q->rows() returns 0.
$q->row(n) returns an empty array.
$q->field(n,col) returns "".
$q->insert_id() returns NULL.
$q->affected_rows() returns NULL.
After an INSERT
===============
If successful:
$q->success() returns true.
$q->rows() returns NULL.
$q->row(n) returns an empty array.
$q->field(n,col) returns "".
$q->insert_id() returns the last_insert_id (if there's AUTO_INCREMENT on a column).
$q->affected_rows() returns 1.
After an UPDATE
===============
If rows have been changed:
$q->success() returns true.
$q->rows() returns NULL.
$q->row(n) returns an empty array.
$q->field(n,col) returns "".
$q->insert_id() returns 0.
$q->affected_rows() returns the number of rows changed.
After a DELETE
==============
If rows have been deleted:
$q->success() returns true.
$q->rows() returns NULL.
$q->row(n) returns an empty array.
$q->field(n,col) returns "".
$q->insert_id() returns 0.
$q->affected_rows() returns the number of rows changed.
If no rows are deleted:
$q->success() returns true.
$q->rows() returns NULL.
$q->row(n) returns an empty array.
$q->field(n,col) returns "".
$q->insert_id() returns 0.
$q->affected_rows() returns 0.
If there's an error for any of the above actions:
$q->success() returns false.
$q->rows() returns NULL.
$q->row(n) returns an empty array.
$q->field(n,col) returns "".
$q->insert_id() returns NULL.
$q->affected_rows() returns NULL.
*/
// We'll add up the times of each query so we can output the page total at the end.
global $mysqltotalduration;
$mysqltotalduration = 0.0;
Class MySQLQuery {
public $success = true;
public $rows = NULL;
public $data = array();
public $insert_id = NULL;
public $affected_rows = NULL;
public function __construct($conn) {
$this->conn = $conn;
}
public function query($sql="", $params = NULL) {
if (empty($sql)) {
$this->success = false;
return;
}
if (empty($this->conn)) {
$this->success = false;
return;
}
twfy_debug ("SQL", $sql);
twfy_debug ("SQL", print_r($params, 1));
if ($params !== NULL) {
// Prepare and execute a statement
$pdoStatement = $this->conn->prepare($sql);
foreach ($params as $paramKey => $paramValue) {
if (is_int($paramValue)) {
$paramType = PDO::PARAM_INT;
} else {
$paramType = PDO::PARAM_STR;
}
$pdoStatement->bindValue($paramKey, $paramValue, $paramType);
}
$pdoStatement->execute();
} else {
// Execute the raw query
$pdoStatement = $this->conn->query($sql);
}
// Test the query actually worked
if (!$pdoStatement) {
$this->error($this->conn->errorCode() . ': ' . $this->conn->errorInfo()[2]);
}
if (!$this->success) return;
if ( (!$pdoStatement) or (empty($pdoStatement)) ) {
// A failed query.
$this->success = false;
} else {
// A successful SELECT, SHOW, EXPLAIN or DESCRIBE query.
$this->success = true;
$result = $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
$this->rows = count($result);
$this->data = $result;
// Sanity check that lastInsertId() is actually a number, otherwise panic
if (is_numeric($this->conn->lastInsertId())) {
$this->insert_id = (int) $this->conn->lastInsertId();
} else {
throw new Exception('Last connection ID was not numeric!');
}
$this->affected_rows = $pdoStatement->rowCount();
twfy_debug ("SQLRESULT", array($this, '_display_result'));
// mysql_free_result($q);
}
}
public function success() {
return $this->success;
}
// After INSERTS.
public function insert_id() {
return $this->insert_id;
}
// After INSERT, UPDATE, DELETE.
public function affected_rows() {
return $this->affected_rows;
}
// After SELECT.
public function field($row_index, $column_name) {
if ($this->rows > 0)
return $this->data[$row_index][$column_name];
return "";
}
// After SELECT.
public function rows() {
return $this->rows;
}
// After SELECT.
public function row($row_index) {
if ($this->success && $this->rows > 0)
return $this->data[$row_index];
return array();
}
# Used when debugging
public function _display_result() {
$html = "";
if ($this->rows > 0) {
$html .= "<table border=\"1\">\n<tr>\n";
foreach (array_keys($this->data[0]) as $fieldname) {
$html .= "<th>" . _htmlentities($fieldname) . "</th>";
}
$html .= "</tr>\n";
foreach ($this->data as $index => $row) {
$html .= "<tr>";
foreach ($row as $n => $field) {
if ($n == "email" || $n == "password" || $n == "postcode") {
// Don't want to risk this data being displayed on any page.
$html .= "<td>**MASKED**</td>";
} else {
$html .= "<td>" . _htmlentities($field) . "</td>";
}
}
$html .= "</tr>\n";
}
$html .= "</table>\n";
}
return $html;
}
public function error($errormsg) {
// When a query goes wrong...
$this->success = false;
trigger_error($errormsg, E_USER_ERROR);
}
// End MySQLQuery class
}
$global_connection = null;
Class MySQL {
public function init($db_host, $db_user, $db_pass, $db_name) {
global $global_connection;
// These vars come from config.php.
if (!$global_connection) {
$dsn = 'mysql:dbname=' . $db_name . ';host=' . $db_host;
try {
$conn = new PDO($dsn, $db_user, $db_pass);
} catch (PDOException $e) {
$this->fatal_error('We were unable to connect to the TheyWorkForYou database for some reason. Please try again in a few minutes.');
}
$global_connection = $conn;
}
$this->conn = $global_connection;
return true;
}
public function quote($string) {
return $this->conn->quote($string);
}
public function query($sql, $params = NULL) {
// Pass it an SQL query and if the query was successful
// it returns a MySQLQuery object which you can get results from.
$start = getmicrotime();
$q = new MySQLQuery($this->conn);
$q->query($sql, $params);
$duration = getmicrotime() - $start;
global $mysqltotalduration;
$mysqltotalduration += $duration;
twfy_debug ("SQL", "Complete after $duration seconds.");
// We could also output $q->mysql_info() here, but that's for
// PHP >= 4.3.0.
return $q;
}
// Call at the end of a page.
public function display_total_duration() {
global $mysqltotalduration;
twfy_debug ("TIME", "Total time for MySQL queries on this page: " . $mysqltotalduration . " seconds.");
}
public function fatal_error($error) {
echo '
<html><head><title>TheyWorkForYou - Database Error</title></head>
<body>
<h1><a href="/"><img border="0" src="/images/theyworkforyoucom.gif" width="293" height="28" alt="TheyWorkForYou"></a></h1>
<h2>Database error</h2>
';
echo "<p>$error</p>";
echo '</body></html>';
exit;
}
// End MySQL class
}