-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.php
304 lines (243 loc) · 8 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
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
<?php
/**
* Standalone database connector
*
* @author Jamison Lu
*
*/
class Database{
//Default config setting
var $config = array(
'host' => 'localhost',
'port' => 3306
);
var $mysqli;
var $table_name;
var $debug_mode = TRUE;
//Query settings
var $limit = 25;
var $offset = 0;
var $order = "`id` ASC";
var $models = array();
//************************ Public functions ****************************//
/**
* Constructor
*/
public function __construct($config){
$this->config = $config;
}
/*
* Dynamic method to handle all calls
*/
public function __call($name, $augments){
if(!empty($this->table_name)){
//Handles $this->by_{fields}
if($result = $this->find('by_', $name, $augments)){
return $result;
}
//Handles $this->first_by_{fields}
if($result = $this->find('first_by_', $name, $augments, true)){
return $result;
}
//Get all record
if(preg_match('/all/', $name)){
return $this->get('', $augments[0], $augments[1], $augments[2]);
}
return NULL;
}else{
return NULL;
}
}
/*
* Get table model
*/
public function __get($name){
//Make sure this is a generic database class
//and the naming convention is used
if(empty($this->table_name) && preg_match('/get_/', $name)){
$table_name = preg_replace('/get_(.*)/', '$1', $name);
//Check to see if a model exist already
if( empty( $this->models[$table_name] ) ){
//Contruct model using a new database connection
$model = new Database($this->config);
$model->table_name = $table_name;
$this->models[$table_name] = $model;
return $model;
}else{
//Use existing model
return $this->models[$table_name];
}
}
return NULL;
}
/*
* Generic method for retrieving data
*/
public function get($where = '', $order = '', $limit = '', $offset = ''){
//Format values
$this->get_value(&$order, $this->order);
$this->get_value(&$limit, $this->limit);
$this->get_value(&$offset, $this->offset);
$query = "SELECT * FROM `$this->table_name` $where ORDER BY $order LIMIT $offset, $limit";
//Outputs query for debug purpose
if($this->debug_mode){
echo $query.'<br/>';
}
return $this->query_result($query);
}
//************************ Protected functions ****************************//
/*
* Establish and store database connection
*/
protected function connect(){
//Establish connection
$this->mysqli = new mysqli(
$this->config['host'],
$this->config['username'],
$this->config['password'],
$this->config['database'],
$this->config['port']
);
$this->throwExceptionOnError();
}
/*
* Prepare database query
*/
protected function query($query){
//Initiate database connection
$this->connect();
$this->mysqli->set_charset("utf8");
//Setup query
$stmt = $this->mysqli->prepare($query);
$this->throwExceptionOnError();
//Execute query
$stmt->execute();
$this->throwExceptionOnError();
return $stmt;
}
/*
* Retrieve results of any query execution
*
* Usage:
*
* $rows = $this->query_result('SELECT * FROM Table');
* echo $rows[0]->id;
*/
protected function query_result($query){
//Process and return statement
$stmt = $this->query($query);
$rows = $this->get_result($stmt);
return $rows;
}
/*
* Sort record values into array format
*/
protected function stmt_bind_assoc (&$stmt, &$out) {
$data = $stmt->result_metadata();
$fields = array();
$out = array();
$count = 0;
//Loop through all fields
while($field = $data->fetch_field()) {
$fields[$count] = &$out[$field->name];
$fields[$count] = $fields[$count];
$count++;
}
call_user_func_array(array($stmt, "bind_result"), $fields);
}
/*
* Process and return rows in array format from a statement
*/
protected function get_result($stmt){
$this->stmt_bind_assoc($stmt, $row);
$rows = array();
// loop through all result rows
while ($stmt->fetch()) {
//Store record in object format
$rows[] = (object) $row;
//Setup new row
$row = array();
//Pass record info into the row
$this->stmt_bind_assoc($stmt, $row);
}
$this->throwExceptionOnError();
$stmt->free_result();
$this->mysqli->close();
//Return list of rows/records
return $rows;
}
/*
* Dynamically contruct MySQL where statement
*/
protected function contruct_where($raw_fields, $augments, $max_augments){
$fields = explode('_AND_', $raw_fields);
$where = 'WHERE ';
$count = 0;
foreach($fields as $field){
if($count > 0){
$where .= ' AND ';
}
$where .= "$field = '$augments[$count]'";
$count++;
}
//Store the maximum augments for getting order, offest, limit
$max_augments = $count + 3;
return $where;
}
/*
* Query and return result
*/
protected function find($filter, $name, $augments, $single_record = false){
//Make sure the naming convention is correct
if(preg_match('/^'.$filter.'/', $name)){
$raw_fields = preg_replace('/^'.$filter.'(.*)/', '$1', $name);
$result = array();
//Make sure there are fields specified
if(!empty($raw_fields)){
$max_augments = 0;
$where = $this->contruct_where($raw_fields, $augments, &$max_augments);
$order = $augments[$max_augments - 3];
$limit = $augments[$max_augments - 2];
$offset = $augments[$max_augments - 1];
//Query one record only
if($single_record){
$limit = 1;
}
$result = $this->get($where, $order, $limit, $offset);
}
if($single_record){
//Make sure there are results
if(sizeof($result) > 0){
//return single record
return $result[0];
}else{
//returns empty class;
return new stdClass;
}
}else{
return $result;
}
}else{
return FALSE;
}
}
/*
* Make sure the value is not empty
*/
protected function get_value($value, $default){
if(empty($value)){
$value = $default;
}
}
/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
protected function throwExceptionOnError() {
if($this->mysqli->error && debug_mode) {
$msg = $this->mysqli->errno . ": " . $this->mysqli->error;
throw new Exception('MySQL Error - '. $msg);
}
}
}
?>