forked from ThingEngineer/PHP-MySQLi-Database-Class
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MysqliDb.php
1876 lines (1654 loc) · 52.5 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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* MysqliDb Class
*
* @category Database Access
* @package MysqliDb
* @author Jeffery Way <[email protected]>
* @author Josh Campbell <[email protected]>
* @author Alexander V. Butenko <[email protected]>
* @copyright Copyright (c) 2010
* @license http://opensource.org/licenses/gpl-3.0.html GNU Public License
* @link http://github.com/joshcam/PHP-MySQLi-Database-Class
* @version 2.6-master
*/
class MysqliDb
{
/**
* Static instance of self
* @var MysqliDb
*/
protected static $_instance;
/**
* Table prefix
* @var string
*/
public static $prefix = '';
/**
* MySQLi instance
* @var mysqli
*/
protected $_mysqli;
/**
* The SQL query to be prepared and executed
* @var string
*/
protected $_query;
/**
* The previously executed SQL query
* @var string
*/
protected $_lastQuery;
/**
* The SQL query options required after SELECT, INSERT, UPDATE or DELETE
* @var string
*/
protected $_queryOptions = array();
/**
* An array that holds where joins
* @var array
*/
protected $_join = array();
/**
* An array that holds where conditions
* @var array
*/
protected $_where = array();
/**
* An array that holds having conditions
* @var array
*/
protected $_having = array();
/**
* Dynamic type list for order by condition value
* @var array
*/
protected $_orderBy = array();
/**
* Dynamic type list for group by condition value
* @var array
*/
protected $_groupBy = array();
/**
* Dynamic array that holds a combination of where condition/table data value types and parameter references
* @var array
*/
protected $_bindParams = array(''); // Create the empty 0 index
/**
* Variable which holds an amount of returned rows during get/getOne/select queries
* @var string
*/
public $count = 0;
/**
* Variable which holds an amount of returned rows during get/getOne/select queries with withTotalCount()
* @var string
*/
public $totalCount = 0;
/**
* Variable which holds last statement error
* @var string
*/
protected $_stmtError;
/**
* Database credentials
* @var string
*/
protected $host;
protected $username;
protected $password;
protected $db;
protected $port;
protected $charset;
/**
* Is Subquery object
* @var bool
*/
protected $isSubQuery = false;
/**
* Name of the auto increment column
* @var int
*/
protected $_lastInsertId = null;
/**
* Column names for update when using onDuplicate method
* @var array
*/
protected $_updateColumns = null;
/**
* Return type: 'array' to return results as array, 'object' as object
* 'json' as json string
* @var string
*/
public $returnType = 'array';
/**
* Should join() results be nested by table
* @var bool
*/
protected $_nestJoin = false;
/**
* Table name (with prefix, if used)
* @var string
*/
private $_tableName = '';
/**
* FOR UPDATE flag
* @var bool
*/
protected $_forUpdate = false;
/**
* LOCK IN SHARE MODE flag
* @var bool
*/
protected $_lockInShareMode = false;
/**
* Key field for Map()'ed result array
* @var string
*/
protected $_mapKey = null;
/**
* Variables for query execution tracing
*/
protected $traceStartQ;
protected $traceEnabled;
protected $traceStripPrefix;
public $trace = array();
/**
* Per page limit for pagination
*
* @var int
*/
public $pageLimit = 20;
/**
* Variable that holds total pages count of last paginate() query
*
* @var int
*/
public $totalPages = 0;
/**
* @param string $host
* @param string $username
* @param string $password
* @param string $db
* @param int $port
* @param string $charset
*/
public function __construct($host = null, $username = null, $password = null, $db = null, $port = null, $charset = 'utf8')
{
$isSubQuery = false;
// if params were passed as array
if (is_array($host)) {
foreach ($host as $key => $val) {
$$key = $val;
}
}
// if host were set as mysqli socket
if (is_object($host)) {
$this->_mysqli = $host;
} else {
$this->host = $host;
}
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->port = $port;
$this->charset = $charset;
if ($isSubQuery) {
$this->isSubQuery = true;
return;
}
if (isset($prefix)) {
$this->setPrefix($prefix);
}
self::$_instance = $this;
}
/**
* A method to connect to the database
*
* @throws Exception
* @return void
*/
public function connect()
{
if ($this->isSubQuery) {
return;
}
if (empty($this->host)) {
throw new Exception('MySQL host is not set');
}
$this->_mysqli = new mysqli($this->host, $this->username, $this->password, $this->db, $this->port);
if ($this->_mysqli->connect_error) {
throw new Exception('Connect Error ' . $this->_mysqli->connect_errno . ': ' . $this->_mysqli->connect_error);
}
if ($this->charset) {
$this->_mysqli->set_charset($this->charset);
}
}
/**
* A method to get mysqli object or create it in case needed
*
* @return mysqli
*/
public function mysqli()
{
if (!$this->_mysqli) {
$this->connect();
}
return $this->_mysqli;
}
/**
* 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 MysqliDb Returns the current instance.
*/
public static function getInstance()
{
return self::$_instance;
}
/**
* Reset states after an execution
*
* @return MysqliDb Returns the current instance.
*/
protected function reset()
{
if ($this->traceEnabled) {
$this->trace[] = array($this->_lastQuery, (microtime(true) - $this->traceStartQ), $this->_traceGetCaller());
}
$this->_where = array();
$this->_having = array();
$this->_join = array();
$this->_orderBy = array();
$this->_groupBy = array();
$this->_bindParams = array(''); // Create the empty 0 index
$this->_query = null;
$this->_queryOptions = array();
$this->returnType = 'array';
$this->_nestJoin = false;
$this->_forUpdate = false;
$this->_lockInShareMode = false;
$this->_tableName = '';
$this->_lastInsertId = null;
$this->_updateColumns = null;
$this->_mapKey = null;
}
/**
* Helper function to create dbObject with JSON return type
*
* @return MysqliDb
*/
public function jsonBuilder()
{
$this->returnType = 'json';
return $this;
}
/**
* Helper function to create dbObject with array return type
* Added for consistency as thats default output type
*
* @return MysqliDb
*/
public function arrayBuilder()
{
$this->returnType = 'array';
return $this;
}
/**
* Helper function to create dbObject with object return type.
*
* @return MysqliDb
*/
public function objectBuilder()
{
$this->returnType = 'object';
return $this;
}
/**
* Method to set a prefix
*
* @param string $prefix Contains a tableprefix
*
* @return MysqliDb
*/
public function setPrefix($prefix = '')
{
self::$prefix = $prefix;
return $this;
}
/**
* Execute raw SQL query.
*
* @param string $query User-provided query to execute.
* @param array $bindParams Variables array to bind to the SQL statement.
*
* @return array Contains the returned rows from the query.
*/
public function rawQuery($query, $bindParams = null)
{
$params = array(''); // Create the empty 0 index
$this->_query = $query;
$stmt = $this->_prepareQuery();
if (is_array($bindParams) === true) {
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->count = $stmt->affected_rows;
$this->_stmtError = $stmt->error;
$this->_lastQuery = $this->replacePlaceHolders($this->_query, $params);
$res = $this->_dynamicBindResults($stmt);
$this->reset();
return $res;
}
/**
* Helper function to execute raw SQL query and return only 1 row of results.
* Note that function do not add 'limit 1' to the query by itself
* Same idea as getOne()
*
* @param string $query User-provided query to execute.
* @param array $bindParams Variables array to bind to the SQL statement.
*
* @return array|null Contains the returned row from the query.
*/
public function rawQueryOne($query, $bindParams = null)
{
$res = $this->rawQuery($query, $bindParams);
if (is_array($res) && isset($res[0])) {
return $res[0];
}
return null;
}
/**
* Helper function to execute raw SQL query and return only 1 column of results.
* If 'limit 1' will be found, then string will be returned instead of array
* Same idea as getValue()
*
* @param string $query User-provided query to execute.
* @param array $bindParams Variables array to bind to the SQL statement.
*
* @return mixed Contains the returned rows from the query.
*/
public function rawQueryValue($query, $bindParams = null)
{
$res = $this->rawQuery($query, $bindParams);
if (!$res) {
return null;
}
$limit = preg_match('/limit\s+1;?$/i', $query);
$key = key($res[0]);
if (isset($res[0][$key]) && $limit == true) {
return $res[0][$key];
}
$newRes = Array();
for ($i = 0; $i < $this->count; $i++) {
$newRes[] = $res[$i][$key];
}
return $newRes;
}
/**
* A method to perform select query
*
* @param string $query Contains a user-provided select query.
* @param int|array $numRows Array to define SQL limit in format Array ($count, $offset)
*
* @return array Contains the returned rows from the query.
*/
public function query($query, $numRows = null)
{
$this->_query = $query;
$stmt = $this->_buildQuery($numRows);
$stmt->execute();
$this->_stmtError = $stmt->error;
$res = $this->_dynamicBindResults($stmt);
$this->reset();
return $res;
}
/**
* This method allows you to specify multiple (method chaining optional) options for SQL queries.
*
* @uses $MySqliDb->setQueryOption('name');
*
* @param string|array $options The optons name of the query.
*
* @throws Exception
* @return MysqliDb
*/
public function setQueryOption($options)
{
$allowedOptions = Array('ALL', 'DISTINCT', 'DISTINCTROW', 'HIGH_PRIORITY', 'STRAIGHT_JOIN', 'SQL_SMALL_RESULT',
'SQL_BIG_RESULT', 'SQL_BUFFER_RESULT', 'SQL_CACHE', 'SQL_NO_CACHE', 'SQL_CALC_FOUND_ROWS',
'LOW_PRIORITY', 'IGNORE', 'QUICK', 'MYSQLI_NESTJOIN', 'FOR UPDATE', 'LOCK IN SHARE MODE');
if (!is_array($options)) {
$options = Array($options);
}
foreach ($options as $option) {
$option = strtoupper($option);
if (!in_array($option, $allowedOptions)) {
throw new Exception('Wrong query option: ' . $option);
}
if ($option == 'MYSQLI_NESTJOIN') {
$this->_nestJoin = true;
} elseif ($option == 'FOR UPDATE') {
$this->_forUpdate = true;
} elseif ($option == 'LOCK IN SHARE MODE') {
$this->_lockInShareMode = true;
} else {
$this->_queryOptions[] = $option;
}
}
return $this;
}
/**
* Function to enable SQL_CALC_FOUND_ROWS in the get queries
*
* @return MysqliDb
*/
public function withTotalCount()
{
$this->setQueryOption('SQL_CALC_FOUND_ROWS');
return $this;
}
/**
* A convenient SELECT * function.
*
* @param string $tableName The name of the database table to work with.
* @param int|array $numRows Array to define SQL limit in format Array ($count, $offset)
* or only $count
* @param string $columns Desired columns
*
* @return array Contains the returned rows from the select query.
*/
public function get($tableName, $numRows = null, $columns = '*')
{
if (empty($columns)) {
$columns = '*';
}
$column = is_array($columns) ? implode(', ', $columns) : $columns;
if (strpos($tableName, '.') === false) {
$this->_tableName = self::$prefix . $tableName;
} else {
$this->_tableName = $tableName;
}
$this->_query = 'SELECT ' . implode(' ', $this->_queryOptions) . ' ' .
$column . " FROM " . $this->_tableName;
$stmt = $this->_buildQuery($numRows);
if ($this->isSubQuery) {
return $this;
}
$stmt->execute();
$this->_stmtError = $stmt->error;
$res = $this->_dynamicBindResults($stmt);
$this->reset();
return $res;
}
/**
* A convenient SELECT * function to get one record.
*
* @param string $tableName The name of the database table to work with.
* @param string $columns Desired columns
*
* @return array Contains the returned rows from the select query.
*/
public function getOne($tableName, $columns = '*')
{
$res = $this->get($tableName, 1, $columns);
if ($res instanceof MysqliDb) {
return $res;
} elseif (is_array($res) && isset($res[0])) {
return $res[0];
} elseif ($res) {
return $res;
}
return null;
}
/**
* A convenient SELECT COLUMN function to get a single column value from one row
*
* @param string $tableName The name of the database table to work with.
* @param string $column The desired column
* @param int $limit Limit of rows to select. Use null for unlimited..1 by default
*
* @return mixed Contains the value of a returned column / array of values
*/
public function getValue($tableName, $column, $limit = 1)
{
$res = $this->ArrayBuilder()->get($tableName, $limit, "{$column} AS retval");
if (!$res) {
return null;
}
if ($limit == 1) {
if (isset($res[0]["retval"])) {
return $res[0]["retval"];
}
return null;
}
$newRes = Array();
for ($i = 0; $i < $this->count; $i++) {
$newRes[] = $res[$i]['retval'];
}
return $newRes;
}
/**
* Insert method to add new row
*
* @param string $tableName The name of the table.
* @param array $insertData Data containing information for inserting into the DB.
*
* @return bool Boolean indicating whether the insert query was completed succesfully.
*/
public function insert($tableName, $insertData)
{
return $this->_buildInsert($tableName, $insertData, 'INSERT');
}
/**
* Replace method to add new row
*
* @param string $tableName The name of the table.
* @param array $insertData Data containing information for inserting into the DB.
*
* @return bool Boolean indicating whether the insert query was completed succesfully.
*/
public function replace($tableName, $insertData)
{
return $this->_buildInsert($tableName, $insertData, 'REPLACE');
}
/**
* A convenient function that returns TRUE if exists at least an element that
* satisfy the where condition specified calling the "where" method before this one.
*
* @param string $tableName The name of the database table to work with.
*
* @return array Contains the returned rows from the select query.
*/
public function has($tableName)
{
$this->getOne($tableName, '1');
return $this->count >= 1;
}
/**
* 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.
* @param int $numRows Limit on the number of rows that can be updated.
*
* @return bool
*/
public function update($tableName, $tableData, $numRows = null)
{
if ($this->isSubQuery) {
return;
}
$this->_query = "UPDATE " . self::$prefix . $tableName;
$stmt = $this->_buildQuery($numRows, $tableData);
$status = $stmt->execute();
$this->reset();
$this->_stmtError = $stmt->error;
$this->count = $stmt->affected_rows;
return $status;
}
/**
* Delete query. Call the "where" method first.
*
* @param string $tableName The name of the database table to work with.
* @param int|array $numRows Array to define SQL limit in format Array ($count, $offset)
* or only $count
*
* @return bool Indicates success. 0 or 1.
*/
public function delete($tableName, $numRows = null)
{
if ($this->isSubQuery) {
return;
}
$table = self::$prefix . $tableName;
if (count($this->_join)) {
$this->_query = "DELETE " . preg_replace('/.* (.*)/', '$1', $table) . " FROM " . $table;
} else {
$this->_query = "DELETE FROM " . $table;
}
$stmt = $this->_buildQuery($numRows);
$stmt->execute();
$this->_stmtError = $stmt->error;
$this->reset();
return ($stmt->affected_rows > 0);
}
/**
* This method allows you to specify multiple (method chaining optional) AND 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.
* @param string $operator Comparison operator. Default is =
* @param string $cond Condition of where statement (OR, AND)
*
* @return MysqliDb
*/
public function where($whereProp, $whereValue = 'DBNULL', $operator = '=', $cond = 'AND')
{
// forkaround for an old operation api
if (is_array($whereValue) && ($key = key($whereValue)) != "0") {
$operator = $key;
$whereValue = $whereValue[$key];
}
if (count($this->_where) == 0) {
$cond = '';
}
$this->_where[] = array($cond, $whereProp, $operator, $whereValue);
return $this;
}
/**
* This function store update column's name and column name of the
* autoincrement column
*
* @param array $updateColumns Variable with values
* @param string $lastInsertId Variable value
*
* @return MysqliDb
*/
public function onDuplicate($updateColumns, $lastInsertId = null)
{
$this->_lastInsertId = $lastInsertId;
$this->_updateColumns = $updateColumns;
return $this;
}
/**
* This method allows you to specify multiple (method chaining optional) OR WHERE statements for SQL queries.
*
* @uses $MySqliDb->orWhere('id', 7)->orWhere('title', 'MyTitle');
*
* @param string $whereProp The name of the database field.
* @param mixed $whereValue The value of the database field.
* @param string $operator Comparison operator. Default is =
*
* @return MysqliDb
*/
public function orWhere($whereProp, $whereValue = 'DBNULL', $operator = '=')
{
return $this->where($whereProp, $whereValue, $operator, 'OR');
}
/**
* This method allows you to specify multiple (method chaining optional) AND HAVING statements for SQL queries.
*
* @uses $MySqliDb->having('SUM(tags) > 10')
*
* @param string $havingProp The name of the database field.
* @param mixed $havingValue The value of the database field.
* @param string $operator Comparison operator. Default is =
*
* @return MysqliDb
*/
public function having($havingProp, $havingValue = null, $operator = null)
{
if ($operator) {
$havingValue = array($operator => $havingValue);
}
$this->_having[] = array("AND", $havingValue, $havingProp);
return $this;
}
/**
* This method allows you to specify multiple (method chaining optional) OR HAVING statements for SQL queries.
*
* @uses $MySqliDb->orHaving('SUM(tags) > 10')
*
* @param string $havingProp The name of the database field.
* @param mixed $havingValue The value of the database field.
* @param string $operator Comparison operator. Default is =
*
* @return MysqliDb
*/
public function orHaving($havingProp, $havingValue = null, $operator = null)
{
if ($operator) {
$havingValue = Array($operator => $havingValue);
}
$this->_having[] = Array("OR", $havingValue, $havingProp);
return $this;
}
/**
* This method allows you to concatenate joins for the final SQL statement.
*
* @uses $MySqliDb->join('table1', 'field1 <> field2', 'LEFT')
*
* @param string $joinTable The name of the table.
* @param string $joinCondition the condition.
* @param string $joinType 'LEFT', 'INNER' etc.
*
* @throws Exception
* @return MysqliDb
*/
public function join($joinTable, $joinCondition, $joinType = '')
{
$allowedTypes = array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER');
$joinType = strtoupper(trim($joinType));
if ($joinType && !in_array($joinType, $allowedTypes)) {
throw new Exception('Wrong JOIN type: ' . $joinType);
}
if (!is_object($joinTable)) {
$joinTable = self::$prefix . $joinTable;
}
$this->_join[] = Array($joinType, $joinTable, $joinCondition);
return $this;
}
/**
* This method allows you to specify multiple (method chaining optional) ORDER BY statements for SQL queries.
*
* @uses $MySqliDb->orderBy('id', 'desc')->orderBy('name', 'desc');
*
* @param string $orderByField The name of the database field.
* @param string $orderByDirection Order direction.
* @param array $customFields Fieldset for ORDER BY FIELD() ordering
*
* @throws Exception
* @return MysqliDb
*/
public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null)
{
$allowedDirection = Array("ASC", "DESC");
$orderbyDirection = strtoupper(trim($orderbyDirection));
$orderByField = preg_replace("/[^-a-z0-9\.\(\),_`\*\'\"]+/i", '', $orderByField);
// Add table prefix to orderByField if needed.
//FIXME: We are adding prefix only if table is enclosed into `` to distinguish aliases
// from table names
$orderByField = preg_replace('/(\`)([`a-zA-Z0-9_]*\.)/', '\1' . self::$prefix . '\2', $orderByField);
if (empty($orderbyDirection) || !in_array($orderbyDirection, $allowedDirection)) {
throw new Exception('Wrong order direction: ' . $orderbyDirection);
}
if (is_array($customFields)) {
foreach ($customFields as $key => $value) {
$customFields[$key] = preg_replace("/[^-a-z0-9\.\(\),_`]+/i", '', $value);
}
$orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFields) . '")';
}
$this->_orderBy[$orderByField] = $orderbyDirection;
return $this;
}
/**
* This method allows you to specify multiple (method chaining optional) GROUP BY statements for SQL queries.
*
* @uses $MySqliDb->groupBy('name');
*
* @param string $groupByField The name of the database field.
*
* @return MysqliDb
*/
public function groupBy($groupByField)
{
$groupByField = preg_replace("/[^-a-z0-9\.\(\),_\*]+/i", '', $groupByField);
$this->_groupBy[] = $groupByField;
return $this;
}
/**
* This methods returns the ID of the last inserted item
*
* @return int 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);
}
/**
* Method to call mysqli->ping() to keep unused connections open on
* long-running scripts, or to reconnect timed out connections (if php.ini has
* global mysqli.reconnect set to true). Can't do this directly using object
* since _mysqli is protected.
*
* @return bool True if connection is up
*/
public function ping()
{
return $this->mysqli()->ping();
}
/**
* 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 'boolean':
case 'integer':
return 'i';
break;
case 'blob':
return 'b';
break;
case 'double':
return 'd';
break;
}
return '';
}
/**
* Helper function to add variables into bind parameters array
*
* @param string Variable value
*/
protected function _bindParam($value)
{
$this->_bindParams[0] .= $this->_determineType($value);
array_push($this->_bindParams, $value);
}
/**
* Helper function to add variables into bind parameters array in bulk
*
* @param array $values Variable with values
*/
protected function _bindParams($values)
{
foreach ($values as $value) {
$this->_bindParam($value);
}
}
/**
* Helper function to add variables into bind parameters array and will return
* its SQL part of the query according to operator in ' $operator ?' or
* ' $operator ($subquery) ' formats