forked from ThingEngineer/PHP-MySQLi-Database-Class
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMysqliDb.php
450 lines (393 loc) · 11.3 KB
/
MysqliDb.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
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
<?php
/**
* MySqliDb Class
*
* @category Database Access
* @package MysqliDB
* @author Jeffery Way <[email protected]>
* @author Josh Campbell <[email protected]>
* @copyright Copyright (c) 2010
* @license http://opensource.org/licenses/gpl-3.0.html GNU Public License
* @version 1.1
**/
class MysqliDB {
/**
* Static instance of self
*
* @var object
*/
protected static $_instance;
/**
* MySQLi instance
*
* @var object
*/
protected $_mysqli;
/**
* The SQL query to be prepared and executed
*
* @var object
*/
protected $_query;
/**
* An array that holds where conditions 'fieldname' => 'value'
*
* @var array
*/
protected $_where = array();
/**
* Dynamic type list for where condition values
*
* @var array
*/
protected $_whereTypeList;
/**
* Dynamic type list for table data values
*
* @var array
*/
protected $_paramTypeList;
/**
* Dynamic array that holds a combination of where condition/table data value types and parameter referances
*
* @var array
*/
protected $_bindParams = array(''); // Create the empty 0 index
public function __construct($host, $username, $password, $db) {
$this->_mysqli = new mysqli($host, $username, $password, $db)
or die('There was a problem connecting to the database');
self::$_instance = $this;
}
/**
* A method of returning the static instance to allow access to the
* instantiated object from within another class.
* Inheriting this class would require reloading connection info.
*
* @uses $db = MySqliDb::getInstance();
*
* @return object Returns the current instance.
*/
public static function getInstance()
{
return self::$_instance;
}
/**
* Reset states after an execution
*
* @return object Returns the current instance.
*/
protected function reset()
{
$this->_where = array();
$this->_bindParams = array(''); // Create the empty 0 index
unset($this->_query);
unset($this->_whereTypeList);
unset($this->_paramTypeList);
}
/**
* Pass in a raw query and an array containing the parameters to bind to the prepaird statement.
*
* @param string $query Contains a user-provided query.
* @param array $bindData All variables to bind to the SQL statment.
* @return array Contains the returned rows from the query.
*/
public function rawQuery($query, $bindParams = NULL)
{
$this->_query = filter_var($query, FILTER_SANITIZE_STRING);
$stmt = $this->_prepareQuery();
if (gettype($bindParams) === 'array') {
$params = array(''); // Create the empty 0 index
foreach ($bindParams as $prop => $val) {
$params[0] .= $this->_determineType($val);
array_push($params, $bindParams[$prop]);
}
call_user_func_array(array($stmt, "bind_param"),$this->refValues($params));
}
$stmt->execute();
$this->reset();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
*
* @param string $query Contains a user-provided select query.
* @param int $numRows The number of rows total to return.
* @return array Contains the returned rows from the query.
*/
public function query($query, $numRows = NULL)
{
$this->_query = filter_var($query, FILTER_SANITIZE_STRING);
$stmt = $this->_buildQuery($numRows);
$stmt->execute();
$this->reset();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
* A convenient SELECT * function.
*
* @param string $tableName The name of the database table to work with.
* @param integer $numRows The number of rows total to return.
* @return array Contains the returned rows from the select query.
*/
public function get($tableName, $numRows = NULL)
{
$this->_query = "SELECT * FROM $tableName";
$stmt = $this->_buildQuery($numRows);
$stmt->execute();
$this->reset();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
*
* @param <string $tableName The name of the table.
* @param array $insertData Data containing information for inserting into the DB.
* @return boolean Boolean indicating whether the insert query was completed succesfully.
*/
public function insert($tableName, $insertData)
{
$this->_query = "INSERT into $tableName";
$stmt = $this->_buildQuery(NULL, $insertData);
$stmt->execute();
$this->reset();
($stmt->affected_rows) ? $result = $stmt->insert_id : $result = false;
return $result;
}
/**
* Update query. Be sure to first call the "where" method.
*
* @param string $tableName The name of the database table to work with.
* @param array $tableData Array of data to update the desired row.
* @return boolean
*/
public function update($tableName, $tableData)
{
$this->_query = "UPDATE $tableName SET ";
$stmt = $this->_buildQuery(NULL, $tableData);
$stmt->execute();
$this->reset();
($stmt->affected_rows) ? $result = true : $result = false;
return $result;
}
/**
* Delete query. Call the "where" method first.
*
* @param string $tableName The name of the database table to work with.
* @param integer $numRows The number of rows to delete.
* @return boolean Indicates success. 0 or 1.
*/
public function delete($tableName, $numRows = NULL) {
$this->_query = "DELETE FROM $tableName";
$stmt = $this->_buildQuery($numRows);
$stmt->execute();
$this->reset();
($stmt->affected_rows) ? $result = true : $result = false;
return $result;
}
/**
* This method allows you to specify multipl (method chaining optional) WHERE statements for SQL queries.
*
* @uses $MySqliDb->where('id', 7)->where('title', 'MyTitle');
*
* @param string $whereProp The name of the database field.
* @param mixed $whereValue The value of the database field.
*/
public function where($whereProp, $whereValue)
{
$this->_where[$whereProp] = $whereValue;
return $this;
}
/**
* This methods returns the ID of the last inserted item
*
* @return integer The last inserted item ID.
*/
public function getInsertId()
{
return $this->_mysqli->insert_id;
}
/**
* Escape harmful characters which might affect a query.
*
* @param string $str The string to escape.
* @return string The escaped string.
*/
public function escape ( $str )
{
return $this->_mysqli->real_escape_string ( $str );
}
/**
* This method is needed for prepared statements. They require
* the data type of the field to be bound with "i" s", etc.
* This function takes the input, determines what type it is,
* and then updates the param_type.
*
* @param mixed $item Input to determine the type.
* @return string The joined parameter types.
*/
protected function _determineType($item)
{
switch (gettype($item)) {
case 'NULL':
case 'string':
return 's';
break;
case 'integer':
return 'i';
break;
case 'blob':
return 'b';
break;
case 'double':
return 'd';
break;
}
}
/**
* Abstraction method that will compile the WHERE statement,
* any passed update data, and the desired rows.
* It then builds the SQL query.
*
* @param int $numRows The number of rows total to return.
* @param array $tableData Should contain an array of data for updating the database.
* @return object Returns the $stmt object.
*/
protected function _buildQuery($numRows = NULL, $tableData = NULL)
{
(gettype($tableData) === 'array') ? $hasTableData = true : $hasTableData = false;
(!empty($this->_where )) ? $hasConditional = true : $hasConditional = false;
// Did the user call the "where" method?
if (!empty($this->_where)) {
// if update data was passed, filter through and create the SQL query, accordingly.
if ($hasTableData) {
$i = 1;
$pos = strpos($this->_query, 'UPDATE');
if ( $pos !== false) {
foreach ($tableData as $prop => $value) {
// determines what data type the item is, for binding purposes.
$this->_paramTypeList .= $this->_determineType($value);
// prepares the reset of the SQL query.
($i === count($tableData)) ?
$this->_query .= $prop . ' = ?':
$this->_query .= $prop . ' = ?, ';
$i++;
}
}
}
//Prepair the where portion of the query
$this->_query .= ' WHERE ';
$i = 1;
foreach ($this->_where as $column => $value) {
// Determines what data type the where column is, for binding purposes.
$this->_whereTypeList .= $this->_determineType($value);
// Prepares the reset of the SQL query.
($i === count($this->_where)) ?
$this->_query .= $column . ' = ?':
$this->_query .= $column . ' = ? AND ';
$i++;
}
}
// Determine if is INSERT query
if ($hasTableData) {
$pos = strpos($this->_query, 'INSERT');
if ($pos !== false) {
//is insert statement
$keys = array_keys($tableData);
$values = array_values($tableData);
$num = count($keys);
// wrap values in quotes
foreach ($values as $key => $val) {
$values[$key] = "'{$val}'";
$this->_paramTypeList .= $this->_determineType($val);
}
$this->_query .= '(' . implode($keys, ', ') . ')';
$this->_query .= ' VALUES(';
while ($num !== 0) {
($num !== 1) ? $this->_query .= '?, ' : $this->_query .= '?)';
$num--;
}
}
}
// Did the user set a limit
if (isset($numRows)) {
$this->_query .= " LIMIT " . (int) $numRows;
}
// Prepare query
$stmt = $this->_prepareQuery();
// Prepare table data bind parameters
if ($hasTableData) {
$this->_bindParams[0] = $this->_paramTypeList;
foreach ($tableData as $prop => $val) {
array_push($this->_bindParams, $tableData[$prop]);
}
}
// Prepare where condition bind parameters
if($hasConditional) {
if ($this->_where) {
$this->_bindParams[0] .= $this->_whereTypeList;
foreach ($this->_where as $prop => $val) {
array_push($this->_bindParams, $this->_where[$prop]);
}
}
}
// Bind parameters to statment
if ($hasTableData || $hasConditional){
call_user_func_array(array($stmt, "bind_param"),$this->refValues($this->_bindParams));
}
return $stmt;
}
/**
* This helper method takes care of prepared statements' "bind_result method
* , when the number of variables to pass is unknown.
*
* @param object $stmt Equal to the prepared statement object.
* @return array The results of the SQL fetch.
*/
protected function _dynamicBindResults($stmt)
{
$parameters = array();
$results = array();
$meta = $stmt->result_metadata();
$row = array();
while ($field = $meta->fetch_field()) {
$row[$field->name] = NULL;
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, "bind_result"),$parameters);
while ($stmt->fetch()) {
$x = array();
foreach ($row as $key => $val) {
$x[$key] = $val;
}
array_push($results, $x);
}
return $results;
}
/**
* Method attempts to prepare the SQL query
* and throws an error if there was a problem.
*/
protected function _prepareQuery()
{
if (!$stmt = $this->_mysqli->prepare($this->_query)) {
trigger_error("Problem preparing query ($this->_query) ".$this->_mysqli->error, E_USER_ERROR);
}
return $stmt;
}
public function __destruct()
{
$this->_mysqli->close();
}
function refValues($arr)
{
//Reference is required for PHP 5.3+
if (strnatcmp(phpversion(),'5.3') >= 0) {
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
} // END class