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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
| <?php
abstract class Record{
//The tables where the operation will take place
const UPDATE_TABLE = 0; //The table where the record to be updated
const DELETE_TABLE = 1; //The table where the record to be deleted
//Operations against the table/s
const OP_DELETE = 'delete_record';
const OP_UPDATE = 'update_record';
const OP_CREATE = 'create_record';
const OP_READ = 'read_record';
//For type checking
const TYPE_STRING = 'string';
const TYPE_BOOL = 'boolean';
const TYPE_INT = 'integer';
const TYPE_DOUBLE = 'double';
const TYPE_ARRAY = 'array';
const TYPE_OBJECT = 'object';
const TYPE_RESOURCE = 'resource';
const TYPE_NULL = 'NULL';
const TYPE_UNKNOWN = 'unknown type';
//Log types for log4php
const LOG_TYPE_WARN = "WARN";
const LOG_TYPE_INFO = "INFO";
const LOG_TYPE_DEBUG = "DEBUG";
const ID = 'id';
protected $logger;
protected $connection;
/**
* Constructor
* @param connection MySQLi object used to connect to MySQL database
* @param hostname The hostname of the server
* @param username The username to connect to MySQL
* @param passwd The password to connect to MySQL
* @param dbname The database name of MySQL to use
*/
function __construct(mysqli $connection = null,
$hostname = "localhost",
$username = "root",
$passwd = "",
$dbname = "purchase_order"){
if($connection === null)
$this->connection = new mysqli($hostname, $username,
$passwd, $dbname);
else
$this->connection = $connection;
$this->connection->set_charset('utf8');
$this->logger = null;
}
/**
* Set the logger for log4php
* @param logger The logger used for loggin
*/
function setLogger($logger = null){
$this->logger = $logger;
}
/**
* Get the connection for the database
*/
public function getConnection(){
return $this->connection;
}
/**
* Get the connection error description
* @return The error for the connection
*/
public function error(){
return $this->connection->error;
}
/************************************
*RETRIEVE
************************************/
/**
* Custom query without escapes, escape your values before passing into
* this function
* @param fields MySQL fields comma separated
* @param tbl MySQL table comma separated
* @param condition Full MySQL conditions without 'WHERE' keyword
f @param additional An additional MySQL queries, have to be in MySQL
* @return Associative array of results or null on failure
*/
public function select($fields = null, $tbl = null, $condition = null,
$additional = null){
if(!$this->isValidValues(array($fields, $tbl), self::TYPE_STRING))
return null;
$sql = "SELECT $fields FROM $tbl";
$authCond = null;
$auth = $this->isAuthorized(self::OP_READ, $authCond);
if(!$auth){
$this->log('Unauthorized read access!', self::LOG_TYPE_WARN);
return null;
}else if($auth && $authCond != null)
$sql .= " WHERE $authCond";
if($condition != null){
if($authCond != null)
$sql .= " AND $condition $additional";
else
$sql .= " WHERE $condition $additional";
}else
$sql .= " $additional";
$this->log("Executing SQL: $sql", self::LOG_TYPE_DEBUG);
$query = $this->connection->query($sql);
if($query){
$result = $this->fetchAllAssoc($query);
$query->close();
$this->log("Query success: Fetched ". count($result)."rows",
self::LOG_TYPE_DEBUG);
return $result;
}else
$this->log("Query failed: ". $this->error(), self::LOG_TYPE_WARN);
return null;
}
/**
* Get all records with starting records and number of records
* @param start The starting record, default 0
* @param count The number of records, set to 0 to list all, default 0
* @return An associative array based on field name as keys or null on
* failure
*/
public function getAll($start = 0, $count = 0){
$this->log('Retrieving all records', self::LOG_TYPE_INFO);
$fields = null;
$tables = null;
$conditions = null;
$this->getAllQueryStatements($fields, $tables, $conditions);
if(!$this->isValidValues(array($fields, $tables), self::TYPE_STRING))
return null;
if($count != 0)
return $this->select($fields, $tables, $conditions, "LIMIT $start,
$count");
else
return $this->select($fields, $tables, $conditions);
}
/************************************
*CREATE
************************************/
/**
* Insert a record
* @param fields The fields to be inserted
* @return True on success, null on failure
*/
public function insert(array $fields = null){}
/************************************
*UPDATE
************************************/
/**
* Updates a record, using template method.
* At least the 'id' key has to be set.
* @param fields The field/s to be updated
* @see subclass::getUpdateColumns()
*/
public function update(array $fields = null){
$this->log('Updating record', self::LOG_TYPE_INFO);
//Authorization
$authCond = null;
if(!$this->isAuthorized(self::OP_UPDATE, $authCond)){
$this->log('Unauthorized update!', self::LOG_TYPE_WARN);
return null;
}
$table = $this->getTableName(self::UPDATE_TABLE);
$columns = $this->getUpdateColumns($fields, $table);
if($fields === null || !$this->validKeys(array(self::ID), $fields))
return null;
$this->preUpdate($fields[self::ID]);
$result = null;
if($table && count($columns) > 0){
$sql = "UPDATE " . $table . " SET ";
$count = count($columns);
if(isset($columns['conditions']))
$count = count($columns) - 1;
for($i = 0; $i < $count; $i++){
$sql .= $columns[$i];
if($i < $count -1)
$sql .= ", "; //Insert comma if not last element
}
if(!isset($columns['conditions']))
$sql .= " WHERE id=" . $fields[self::ID];
else
$sql .= ' WHERE '. $columns['conditions'];
if($authCond != null)
$sql .= " AND $authCond";
$this->log("Executing SQL: $sql", self::LOG_TYPE_DEBUG);
$result = $this->connection->query($sql);
if(!$result){
$this->log("SQL statement failed: ". $this->error(),
self::LOG_TYPE_WARN);
$result = null;
}else{
$this->log('SQL execution successful!',
self::LOG_TYPE_INFO);
$result = $fields['id'];
}
}else if($table === '' || $table === null){
$this->log('Invalid table name for update!',
self::LOG_TYPE_WARN);
$result = null;
}else if(count($columns) <= 0){
$this->log('No columns returned!', self::LOG_TYPE_WARN);
$result = null;
}else
$this->log('An unknown mutant error has occured! Arghh!!',
self::LOG_TYPE_WARN);
$this->postUpdate($result);
return $result;
}
/************************************
*DELETE
************************************/
/**
* Delete a record
* @param id The id that identifies the record to be deleted
* @return Deleted ID on success null on failure
*/
public function delete($id = null){
if(!$this->isValidValues(array($id), self::TYPE_INT))
return null;
$this->log("Deleting record $id", self::LOG_TYPE_INFO);
$data = null;
$this->preDelete($id);
//Authorization
$authCond = null;
if(!$this->isAuthorized(self::OP_UPDATE, $authCond)){
$this->log('Unauthorized update!', self::LOG_TYPE_WARN);
return null;
}
$sql = "DELETE FROM " . $this->getTableName(self::DELETE_TABLE)
. " WHERE id=$id";
$this->log("Executing SQL: $sql", self::LOG_TYPE_DEBUG);
$result = $this->connection->query($sql);
if(!$result){
$this->log("SQL statement failed: ". $this->error(),
self::LOG_TYPE_WARN);
$result = null;
}else
$result = $id;
$this->postDelete($result);
return $result;
}
/************************************
*TEMPLATE METHOD
************************************/
/**
* Template method for getAll() function
* Modify fields, tables and conditions to suit your need
* @param fields The fields that need to be modified
* @param tables The tables that need to be modified
* @param conditions The conditions that need to be modified (optional)
*/
abstract protected function getAllQueryStatements(&$fields, &$tables,
&$conditions);
/**
* Template method for update() function
* If 'conditions' key is set, it will override the original WHERE clause
* @return array An array of individual 'field'='value' string for SET
* MySQL clause
* @see Record::update()
*/
protected function getUpdateColumns(array &$fields = null){}
/**
* Template method for delete() and update() to get the table name to be
* altered
*/
abstract protected function getTableName($operation);
/**
* Operations before the deletion of a record
* @param id The id of the record to be deleted
*/
protected function preDelete($id){}
/**
* Operations after the deletion of a record
* @param result True on success null on failure
*/
protected function postDelete($result){}
/**
* Operations before the update process
* @param id The id of the record to be deleted
*/
protected function preUpdate($id){}
/**
* Operations after the update process
* @param result True on success null on failure
*/
protected function postUpdate($result){}
/**
* Whether an operation against a record is authorized
*/
protected function isAuthorized($operation = null, &$condition = null){
return true;
}
/************************************
*HANDY UTILITIES
************************************/
/**
* Converts 2D array to 1D array
* @param array The array to convert
* @return A converted 1D array or null on failure
*/
public function toSingleArray(array $array = null){
$this->log('Converting 2D '. count($array) .' to 1D array',
self::LOG_TYPE_INFO);
if($array === null || count($array) == 0)
return null;
$result = array();
foreach($array as $row){
foreach($row as $key => $value)
$result[$key] = $value;
}
$this->log('Conversion resulted in an array size of '. count($result),
self::LOG_TYPE_INFO);
return $result;
}
/**
* Validate if an array of values contain not allowable values, return false if not
* @param requiredKeys The keys that are non-empty and non-null
* @param fields The fields that needed to be checked
* @return True on success or false on violation
*/
public function validKeys(array $requiredKeys = null, array $fields = null){
$this->log('Checking for invalid keys', self::LOG_TYPE_INFO);
if($fields === null || !$requiredKeys){
$this->log('Null array found!', self::LOG_TYPE_WARN);
return false;
}
foreach($requiredKeys as $key){
if(!isset($fields[$key])){
$this->log('Required field key ('. $key .') not found!',
self::LOG_TYPE_WARN);
return false;
}
if($fields[$key] === null){
$this->log('Null not allowed for key ('. $key .')!',
self::LOG_TYPE_WARN);
return false;
}
}
return true;
}
/**
* Check if values are valid and the type of the values
* @param values The values to check against
* @param datatype Accepted data type for $values
* @return True on success or false on violation
*/
public function isValidValues($value = null, $datatype = self::TYPE_STRING){
$this->log('Checking for invalid values (non-'. $datatype .')',
self::LOG_TYPE_INFO);
if($value === null){
$this->log('Null array found! $values can\'t be null!',
self::LOG_TYPE_WARN);
return false;
}
if(gettype($value) == self::TYPE_ARRAY){
foreach($value as $val){
if($val === null || gettype($val) != $datatype){
if(gettype($val) == self::TYPE_ARRAY)
$val = implode(', ', $val);
$this->log('Invalid values found => "'. $val
.'" of type "'. gettype($val) .'"',
self::LOG_TYPE_WARN);
return false;
}
}
}else{
if($value === null || gettype($value) != $datatype){
$this->log('Invalid values found => "'. $value
.'" of type "'. gettype($value) .'"',
self::LOG_TYPE_WARN);
return false;
}
}
return true;
}
/**
* Write to log file
* @param msg The message to write
* @param type The type of log
*/
protected function log($msg = "", $type = self::LOG_TYPE_INFO){
if($this->logger != null){
if($type == self::LOG_TYPE_WARN){
$this->logger->warn($msg);
}else if($type == self::LOG_TYPE_INFO){
$this->logger->info($msg);
}else if($type == self::LOG_TYPE_DEBUG){
$this->logger->debug($msg);
}
}
}
public function fetchAllAssoc($result = null){
if($result === null)
return null;
$assoc = array();
while($row = $result->fetch_assoc()){
$assoc[] = $row;
}
return $assoc;
}
}
?>
|