-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Zebra_Database.php
executable file
·5704 lines (4699 loc) · 240 KB
/
Zebra_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
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
/**
* A compact, lightweight yet feature-rich PHP MySQLi database wrapper providing methods for interacting
* with MySQL databases that are more secure, powerful and intuitive than PHP's default ones.
*
* Can provides debugging information when called from **CLI** (command-line interface) and supports logging queries
* done through **AJAX** requests.
*
* Read more {@link https://github.com/stefangabos/Zebra_Database here}
*
* @author Stefan Gabos <contact@stefangabos.ro>
* @version 2.12.0 (last revision: November 13, 2024)
* @copyright © 2006 - 2024 Stefan Gabos
* @license https://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE
* @package Zebra_Database
*/
class Zebra_Database {
/**
* The number of rows affected after running an `INSERT`, `UPDATE`, `REPLACE` or `DELETE` query.
*
* See the {@link returned_rows} property for getting the number of rows returned by `SELECT` queries.
*
* <code>
* // update some columns in a table
* $db->update('table', array(
* 'column_1' => 'value 1',
* 'column_2' => 'value 2',
* ), 'id = ?', array($id));
*
* // print the number of affected rows
* echo $db->affected_rows;
* </code>
*
* @var integer
*/
public $affected_rows;
/**
* Should escaped variables be also enclosed in single quotes?
*
* Default is `TRUE`
*
* @since 2.9.13
*
* @var boolean
*/
public $auto_quote_replacements = true;
/**
* Path where to store cached queries results.
*
* *The path must be relative to your working path and not the path of this library!*
*
* @var string
*/
public $cache_path;
/**
* The method to be used for caching query results.
*
* Can be either:
*
* - **disk** - query results are cached as files on the disk at the path specified by {@link cache_path}
*
* - **session** - query results are cached in the session (use this only for smaller data sets)<br>
* *When using this method, the library expects an active session and will trigger a fatal error
* otherwise!*
*
* - **memcache** - query results are cached using a {@link https://memcached.org/about memcache} server<br>
* When using this method make sure to also set the appropriate values for {@link memcache_host},
* {@link memcache_port} and optionally {@link memcache_compressed} **prior** to calling the
* {@link connect()} method! Failing to do so will disable caching.
* <br>
* *When using this method, PHP must be compiled with the {@link https://pecl.php.net/package/memcache memcache}
* extension and, if {@link memcache_compressed} property is set to `TRUE`, needs to be configured
* with `--with-zlib[=DIR]`*
*
* - **redis** - query results are cached using a {@link https://redis.io/ redis} server<br>
* When using this method make sure to also set the appropriate values for {@link redis_host},
* {@link redis_port} and optionally {@link redis_compressed} **prior** to calling the
* {@link connect()} method! Failing to do so will disable caching.
* <br>
* *When using this method, PHP must be compiled with the {@link https://pecl.php.net/package/redis redis}
* extension and, if {@link redis_compressed} property is set to `TRUE`, needs to be configured
* with `--with-zlib[=DIR]`*
*
* <code>
* // the host where memcache is listening for connections
* $db->memcache_host = 'localhost';
*
* // the port on which memcache is listening for connections
* $db->memcache_port = 11211;
*
* // for this to work, PHP needs to be configured with --with-zlib[=dir] !
* // set it to FALSE otherwise
* $db->memcache_compressed = true;
*
* // cache queries using the memcache server
* $db->caching_method = 'memcache';
*
* // only now it is the time to connect
* $db->connect(...)
* </code>
*
* *Caching is done on a per-query basis by setting the `cache` argument when calling some of the library's methods
* like {@link query()}, {@link select()}, {@link dcount()}, {@link dlookup()}, {@link dmax()} and {@link dsum()}!*
*
* > Warnings related to the presence of memcache and redis can be disabled by setting the {@link disable_warnings} property.
*
* Default is `disk`
*
* @since 2.7
*
* @var string
*/
public $caching_method = 'disk';
/**
* Turns debugging on or off.
*
* See also {@link $debug_ajax}.
*
* The property can take one of the following values:
*
* - **boolean TRUE**<br>
* Setting this property to a boolean `TRUE` will instruct the library to generate debugging information for each
* query it executes and show the information *on the screen* when script execution ends.
*
* > This is also works when called from CLI!
*
* - **a string**<br>
* Setting this property to a string will instruct the library to turn debugging on when the given string is
* present as argument in the query string (in the URL) and has the value of `1` (i.e `?show_debug=1`)
* <br><br>*Useful for turning debugging on on the fly. If you decide to use this in production, make
* sure to not use an easily guessable value!*<br><br>
* When debugging is turned on this way, a session cookie (a cookie that expires when the browser is closed) will
* also be set so that the query string argument doesn't need to be present for subsequent requests. Debugging
* can also be turned off by setting said query string argument to `0` (i.e `?show_debug=0`). The cookie's name
* can be set via the {@link debug_cookie_name} property.
*
* > This is also works when called from CLI!
*
* - **an array([bool]daily, [bool]hourly, [bool]backtrace)**<br>
* Setting this property to an array like above will instruct the library to generate debugging information for
* each query it executes and write the information to a log file when script execution ends.
*
* - the value of the first entry (daily) indicates whether the log files should be grouped by days or not;
* if set to `TRUE`, log files will have their name in the form of `log_ymd.txt`, where `y`, `m` and `d`
* represent the two digit values of year, month and day, respectively.
*
* - the value of the second entry (hourly) indicates whether the log files should be grouped by hours or not;
* if set to `TRUE`, log files will have their name in the form of `log_ymd_h.txt`, where `y`, `m` and `d`
* represent the two digit values of year, month and day, respectively, while `h` represents the two digit
* value of the hour.<br>
* *Note that if this argument is set to `TRUE`, the first argument will be automatically considered as `TRUE`*
*
* - the value of the third entry (backtrace) indicates whether backtrace information (where the query was
* called from) should also be written to the log file.<br><br>
* *The default values for all the entries is `FALSE` and all are optional, therefore setting the value of
* this property to an empty array is equivalent of setting it to `array(false, false, false)`*
*
* - **boolean FALSE**<br>
* Setting this property to `FALSE` will instruct the library to not generate debugging information for any of the
* queries it executes. Even so, if an error occurs the library will try to log the error to PHP's error log
* file, if your environment is {@link https://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors
* configured to do so} !
*
* > It is highly recommended to set the value of this property to `FALSE` on the production environment. Generating
* the debugging information may consume a lot of resources and is meant to be used **only** in the development process!
*
* <code>
* // log debug information instead of showing it on screen
* // log everything in one single file (not by day/hour) and also show backtrace information
* $db->debug = array(false, false, true)
*
* // disable the generation of debugging information
* $db->debug = false;
*
* // turn debugging on when "debug_db" is found in the query string and has the value "1"
* // (meaning that you have to have ?debug_db=1 in your URL)
* $db->debug = 'debug_db';
* </code>
*
* Default is `TRUE`
*
* @since turning debugging on/off via a query string is available since 2.10.0
*
* @var boolean|string|array<boolean>
*/
public $debug = true;
/**
* Enables logging of queries done through AJAX requests.
*
* When set to `TRUE` all AJAX requests sent by your page will be captured and checked for logs generated by
* `Zebra Database`.
*
* > Note that when this is enabled HTML code will be appended to the result of the AJAX requests!<br>Therefore,
* depending on your use-case, having this enabled could break some of your page's functionality.
*
* Default is `FALSE`
*
* @since 2.11.0
*
* @var boolean
*/
public $debug_ajax = false;
/**
* An array of IP addresses for which to show the debugging console / write to log file, if the {@link debug} property
* is **not** set to `FALSE`.
*
* <code>
* // show the debugging console only to specific IPs
* $db->debugger_ip = array('xxx.xxx.xxx.xxx', 'yyy.yyy.yyy.yyy');
* </code>
*
* Default is an empty array
*
* @since 1.0.6
*
* @var array<string>
*/
public $debugger_ip = array();
/**
* If debugging is enabled on the fly via the presence of a query string argument (see the {@link debug} property),
* a cookie is set so that the query string is not required to be present in subsequent requests.
*
* This property sets that cookie's name.
*
* Default value is `zebra_db`
*
* @since 2.10.0
*
* @var string
*/
public $debug_cookie_name = 'zebra_db';
/**
* Indicates whether {@link https://php.net/manual/en/function.debug-backtrace.php backtrace} information should be
* shown in the debugging console.
*
* Default is `TRUE`
*
* @since 2.5.9
*
* @var boolean
*/
public $debug_show_backtrace = true;
/**
* Show a link for editing the query in your favorite database manager like (like {@link https://www.phpmyadmin.net/ phpMyAdmin}
* or {@link https://www.adminer.org/ Adminer}).
*
* It should be an HTML anchor (a link) to your favorite database manager where you build the query string according
* to the requirements of said database manager using the following placeholders:
*
* - %host%
* - %user%
* - %password%
* - %database%
* - %port%
* - %socket%
* - %query%
*
* ...were any of those placeholders will be replaced by the values you have passed on to {@link connect}, except
* for the *%query%* placeholder which will be replaced by the respective query.
*
* Here's how to set up the value for opening the query in {@link https://www.adminer.org/ Adminer}:
*
* <code>
* <a href="path/to/adminer.php?server=%host%:%port%&db=%database%&sql=%query%" target="adminer">edit in adminer</a>
* </code>
*
* *I don't use {@link https://www.phpmyadmin.net/ phpMyAdmin} so if you manage to set it up, please share the result
* with me so I can add it to the docs. Thanks!*
*
* > Be **VERY CAREFUL** when using this feature and make sure you **do not** expose your credentials in the links
* you build.
*
* Setting it to `false` will disable the feature.
*
* Default is a link to the documentation on how to set the link up.
*
* @since 2.11.0
*
* @var boolean|string
*/
public $debug_show_database_manager = false;
/**
* Indicates whether queries should be {@link https://dev.mysql.com/doc/refman/8.0/en/explain.html EXPLAIN}ed in the
* debugging console.
*
* Default is `TRUE`
*
* @since 2.5.9
*
* @var boolean
*/
public $debug_show_explain = true;
/**
* Indicates which of `$_REQUEST`, `$_POST`, `$_GET`, `$_SESSION`, `$_COOKIE`, `$_FILES` and `$_SERVER` superglobals
* should be available in the debugging console, under the *globals* section.
*
* Can be set to either boolean `TRUE` or `FALSE` as a global setting, or as an associative array where each option's
* visibility can be individually be set, like in the example below:
*
* <code>
* $db->debug_show_globals = array(
* 'request' => true,
* 'post' => true,
* 'get' => true,
* 'session' => true,
* 'cookie' => true,
* 'files' => true,
* 'server' => true,
* );
* </code>
*
* Default is `TRUE`
*
* @since 2.9.14
*
* @var boolean|array<string,boolean>
*/
public $debug_show_globals = true;
/**
* Sets the number of records returned by `SELECT` queries to be shown in the debugging console.
*
* Setting this to `0` or `FALSE` will disable this feature.
*
* <code>
* // show 50 records
* $db->debug_show_records = 50;
* </code>
*
* *Be aware that having this property set to a high number (hundreds) and having queries that di return that many
* rows can cause your script to crash due to memory limitations. In this case you should either lower the value
* of this property or try and set PHP's memory limit higher using:*
*
* <code>
* // set PHP's memory limit to 20 MB
* ini_set('memory_limit','20M');
* </code>
*
* Default is `20`
*
* @since 1.0.9
*
* @var integer
*/
public $debug_show_records = 20;
/**
* By default, if {@link set_charset()} method is not called, caching is used and {@link https://memcached.org/about memcache}
* or {@link https://redis.io/ redis} are available but none of them is used, a warning message will be displayed
* in the debugging console.
*
* The ensure that data is both properly saved and retrieved to and from the database, this method should be called
* first thing after connecting to a database.
*
* If you don't want to call this method nor do you want to see the warning, set this property to `TRUE`
*
* Default is `FALSE`
*
* @var boolean
*/
public $disable_warnings = false;
/**
* After running a `SELECT` query through {@link select()}, {@link query()} or {@link query_unbuffered()} methods and
* having the *calc_rows* argument set to `TRUE`, this property will contain the number of records that **would** have
* been returned **if** there was no `LIMIT` applied to the query.
*
* If *calc_rows* is `FALSE`, or it is `TRUE` but there is no `LIMIT` applied to the query, this property's value
* will be the same as the value of the {@link returned_rows} property.
*
* *For {@link query_unbuffered unbuffered queries} the value of this property will be available **only** after
* iterating over **all** the records with either {@link fetch_assoc()} or {@link fetch_obj()} methods. Until then,
* the value will be **0**!*
*
* <code>
` * // let's assume` that "table" has 100 rows but we're only selecting the first 10 of those
* // the last argument of the method tells the library to get the total number of records in the table
* $db->query('
* SELECT
* *
* FROM
* table
* WHERE
* something = ?
* LIMIT
* 10
* ', array($somevalue), false, true);
*
* // prints "10"
* // as this is the number of records
* // returned by the query
* echo $db->returned_rows;
*
* // prints "100"
* // because we set the "calc_rows" argument of the
* // "query" method to TRUE
* echo $db->found_rows;
* </code>
*
* @var integer|string
*/
public $found_rows;
/**
* When the value of this property is set to `TRUE`, the execution of the script will be halted after the first
* unsuccessful query and the debugging console will be shown (or debug information will be written to the log file if configured
* so), **if** the value of the {@link debug} property is **not** `FALSE` and the viewer's IP address is in the
* {@link debugger_ip} array (or {@link debugger_ip} is an empty array).
*
* > If you want to stop on errors no matter what, set the value of this property to `always` and that will raise an
* exception regardless of the value of the {@link debug} property.<br><br>If you ever consider using this with
* its value set to `always`, I recommend using the {@link debug} property with a string value instead.
*
* <code>
* // don't stop execution for unsuccessful queries (if possible)
* $db->halt_on_errors = false;
* </code>
*
* Default is `TRUE`
*
* @since 1.0.5
*
* @var mixed
*/
public $halt_on_errors = true;
/**
* Path where to store the log files when the {@link debug} property is set to an array OR a callback function to
* pass the log information to instead of being written to a file.
*
* **The path is relative to your working directory.**
*
* *Use `.` (dot) for the current directory instead of an empty string or the log file will be written to the server's
* root.*
*
* If a full path is specified (including an extension) the log file's name will be used from there. Otherwise, the
* log file's name will be `log.txt`
*
* *At the given path the library will attempt to create a file named "log.txt" (or variations as described
* {@link debug here}) so the appropriate rights will need to be granted to the script!*
*
* **IF YOU'RE LOGGING, MAKE SURE YOU HAVE A CRON JOB THAT DELETES THE LOG FILES FROM TIME TO TIME!**
*
* Default is `""` (an empty string) - log files are created in the root of your server.
*
* If you are using a callback function, the function receives the following arguments:
*
* - the debug information, as a string, just like it would go into the log file
* - the backtrace information, as a string, just like it would go into the log file - if {@link debug_show_backtrace}
* is set to `FALSE`, this will be an empty string
*
* @var string
*/
public $log_path = '';
/**
* Time (in seconds) after which a query will be considered as running for too long.
*
* If a query's execution time exceeds this number a notification email will be automatically sent to the address
* defined by {@link notification_address}, having {@link notifier_domain} in subject.
*
* <code>
* // consider queries running for more than 5 seconds as slow and send email
* $db->max_query_time = 5;
* </code>
*
* Default is `10`
*
* @var integer
*/
public $max_query_time = 10;
/**
* Setting this property to `TRUE` will instruct to library to compress the cached results (using `zlib`).
*
* *For this to work, PHP needs to be configured with `--with-zlib[=DIR]`!*
*
* *Set this property only if you are using `memcache` as {@link caching_method}.*
*
* Default is `FALSE`
*
* @since 2.7
*
* @var boolean
*/
public $memcache_compressed = false;
/**
* The host where the memcache server is listening for connections.
*
* *Set this property only if you are using `memcache` as {@link caching_method}.*
*
* Default is `FALSE`
*
* @since 2.7
*
* @var boolean|string
*/
public $memcache_host = false;
/**
* The prefix for the keys used to identify cached queries in memcache. This allows separate caching of the same
* queries by multiple instances of the libraries, or the same instance handling multiple domains on the same
* memcache server.
*
* *Set this property only if you are using `memcache` as {@link caching_method}.*
*
* Default is `""` (an empty string)
*
* @since 2.8.4
*
* @var string
*/
public $memcache_key_prefix = '';
/**
* The port on which the memcache server is listening for connections.
*
* *Set this property only if you are using `memcache` as {@link caching_method}.*
*
* Default is `FALSE`
*
* @since 2.7
*
* @var integer|boolean
*/
public $memcache_port = false;
/**
* By setting this property to `TRUE` a minimized version of the debugging console will be shown by default instead
* of the full-sized one.
*
* Clicking on it will show the full debugging console.
*
* For quick and easy debugging, setting the `highlight` argument of a method that has it will result in the debugging
* console being shown at full size and with the respective query visible for inspecting.
*
* Default is `TRUE`
*
* @since 1.0.4
*
* @var boolean
*/
public $minimize_console = true;
/**
* Email address to which notification emails to be sent when a query's execution time exceeds the number of seconds
* set by {@link max_query_time}. The notification email will be automatically sent to the address defined by
* {@link notification_address} and having {@link notifier_domain} in subject.
*
* > Mails are sent using PHP's {@link https://www.php.net/manual/en/function.mail.php mail} function.
*
* <code>
* // the email address where to send an email when there are slow queries
* $db->notification_address = 'youremail@yourdomain.com';
* </code>
*
* @var string
*/
public $notification_address = '';
/**
* Domain name to be used in the subject of notification emails sent when a query's execution time exceeds the number
* of seconds set by {@link max_query_time}.
*
* If a query's execution time exceeds the number of seconds set by {@link max_query_time}, a notification email
* will be automatically sent to the address defined by {@link notification_address} and having {@link notifier_domain}
* in subject.
*
* > Mails are sent using PHP's {@link https://www.php.net/manual/en/function.mail.php mail} function.
*
* <code>
* // set a domain name so that you'll know where the email comes from
* $db->notifier_domain = 'yourdomain.com';
* </code>
*
* @var string
*/
public $notifier_domain = '';
/**
* Setting this property to `TRUE` will instruct to library to compress the cached results (using `zlib`).
*
* *For this to work, PHP needs to be configured with `--with-zlib[=DIR]`*!
*
* *Set this property only if you are using `redis` as {@link caching_method}.*
*
* Default is `FALSE`
*
* @since 2.10.0
*
* @var boolean
*/
public $redis_compressed = false;
/**
* The host where the redis server is listening for connections.
*
* *Set this property only if you are using `redis` as {@link caching_method}.*
*
* Default is `FALSE`
*
* @since 2.10.0
*
* @var boolean|string
*/
public $redis_host = false;
/**
* The prefix for the keys used to identify cached queries in redis. This allows separate caching of the same
* queries by multiple instances of the libraries, or the same instance handling multiple domains on the same
* redis server.
*
* *Set this property only if you are using `redis` as {@link caching_method}.*
*
* Default is `""` (an empty string)
*
* @since 2.10.0
*
* @var string
*/
public $redis_key_prefix = '';
/**
* The port on which the redis server is listening for connections.
*
* *Set this property only if you are using `redis` as {@link caching_method}.*
*
* Default is `FALSE`
*
* @since 2.10.0
*
* @var integer|boolean
*/
public $redis_port = false;
/**
* Path to parent of public folder containing the `css` and `javascript` folders.
*
* > The path must be relative to your `$_SERVER['DOCUMENT_ROOT']`
*
* @var string
*/
public $resource_path;
/**
* After running a `SELECT` query through {@link select()}, {@link query()} or {@link query_unbuffered()} methods,
* this property will contain the number of returned rows.
*
* *For {@link query_unbuffered unbuffered queries} the value of this property will be available **only** after
* iterating over **all** the records with either {@link fetch_assoc()} or {@link fetch_obj()} methods. Until then,
* the value will be **0**!*
*
* See {@link found_rows} also.
*
* <code>
* $db->query('
* SELECT
* *
* FROM
* table
* WHERE
* something = ?
* LIMIT
* 10
* ', array($somevalue));
*
* // prints "10"
* // as this is the number of records
* // returned by the query
* echo $db->returned_rows;
* </code>
*
* @since 1.0.4
*
* @var integer
*/
public $returned_rows;
/**
* Array with cached results.
*
* We will use this for fetching and seek
*
* @var array<mixed>
* @access private
*/
private $cached_results = array();
/**
* MySQL link identifier.
*
* @var mixed
* @access private
*/
private $connection = false;
/**
* Array that will store the database connection credentials
*
* @var array<string>
* @access private
*/
private $credentials;
/**
* All debugging information is stored in this array.
*
* @var array<mixed>
* @access protected
*/
protected $debug_info = array();
/**
* Stores queries that need to be run once a connection to the database is made
*
* @var array<mixed>
* @access private
*/
private $deferred = array();
/**
* A flag telling the script whether it was called from CLI or in the browser
*
* @var boolean
* @access private
*/
private $is_cli_request = false;
/**
* The language to be used in the debugging console.
*
* Default is "english".
*
* @var string|array<string>
* @access private
*/
private $language = 'english';
/**
* Stores information about the last executed query
*
* @var boolean|integer|object|null
*/
private $last_result;
/**
* Instance of an opened memcache server connection.
*
* @since 2.7
*
* @var mixed
* @access private
*/
private $memcache = false;
/**
* Stores extra connect options that affect behavior for a connection.
*
* @since 2.9.5
*
* @var array<mixed>
* @access private
*/
private $options = array();
/**
* Absolute path to the library, used for includes
*
* Value is set in the constructor!
*
* @var string
* @access private
*/
private $path;
/**
* Instance of an opened redis server connection.
*
* @since 2.10.0
*
* @var mixed
* @access private
*/
private $redis = false;
/**
* Keeps track of the total time used to execute queries
*
* @var float
* @access private
*/
private $total_execution_time = 0;
/**
* Tells whether a transaction is in progress or not.
*
* Possible values are
* - 0, no transaction is in progress
* - 1, a transaction is in progress
* - 2, a transaction is in progress but an error occurred with one of the queries
* - 3, transaction is run in test mode and it will be rolled back upon completion
*
* @var int
* @access private
*/
private $transaction_status = 0;
/**
* Flag telling the library whether to use unbuffered queries or not
*
* @var boolean
* @access private
*/
private $unbuffered = false;
/**
* Array of warnings, generated by the script, to be shown to the user in the debugging console
*
* Default value is set in the constructor!
*
* @var array<string,true>
* @access private
*/
private $warnings;
/**
* All MySQL functions as per {@link https://dev.mysql.com/doc/refman/8.0/en/built-in-function-reference.html}
*
* @var array<mixed>
* @access private
*/
private $mysql_functions = array(
// spell-checker: disable
'ABS', 'ACOS', 'ADDDATE', 'ADDTIME', 'AES_DECRYPT', 'AES_ENCRYPT', 'ANY_VALUE', 'AREA', 'ASBINARY', 'ASWKB', 'ASCII',
'ASIN', 'ASTEXT', 'ASWKT', 'ASYMMETRIC_DECRYPT', 'ASYMMETRIC_DERIVE', 'ASYMMETRIC_ENCRYPT', 'ASYMMETRIC_SIGN',
'ASYMMETRIC_VERIFY', 'ATAN', 'ATAN2', 'ATAN', 'AVG', 'BENCHMARK', 'BIN', 'BIT_AND', 'BIT_COUNT', 'BIT_LENGTH',
'BIT_OR', 'BIT_XOR', 'BUFFER', 'CAST', 'CEIL', 'CEILING', 'CENTROID', 'CHAR', 'CHAR_LENGTH', 'CHARACTER_LENGTH',
'CHARSET', 'COALESCE', 'COERCIBILITY', 'COLLATION', 'COMPRESS', 'CONCAT', 'CONCAT_WS', 'CONNECTION_ID', 'CONTAINS',
'CONV', 'CONVERT', 'CONVERT_TZ', 'CONVEXHULL', 'COS', 'COT', 'COUNT', 'CRC32', 'CREATE_ASYMMETRIC_PRIV_KEY',
'CREATE_ASYMMETRIC_PUB_KEY', 'CREATE_DH_PARAMETERS', 'CREATE_DIGEST', 'CROSSES', 'CURDATE', 'CURRENT_DATE',
'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURTIME', 'DATABASE', 'DATE', 'DATE_ADD', 'DATE_FORMAT',
'DATE_SUB', 'DATEDIFF', 'DAY', 'DAYNAME', 'DAYOFMONTH', 'DAYOFWEEK', 'DAYOFYEAR', 'DECODE', 'DEFAULT', 'DEGREES',
'DES_DECRYPT', 'DES_ENCRYPT', 'DIMENSION', 'DISJOINT', 'DISTANCE', 'ELT', 'ENCODE', 'ENCRYPT', 'ENDPOINT', 'ENVELOPE',
'EQUALS', 'EXP', 'EXPORT_SET', 'EXTERIORRING', 'EXTRACT', 'EXTRACTVALUE', 'FIELD', 'FIND_IN_SET', 'FLOOR', 'FORMAT',
'FOUND_ROWS', 'FROM_BASE64', 'FROM_DAYS', 'FROM_UNIXTIME', 'GEOMCOLLFROMTEXT', 'GEOMETRYCOLLECTIONFROMTEXT',
'GEOMCOLLFROMWKB', 'GEOMETRYCOLLECTIONFROMWKB', 'GEOMETRYCOLLECTION', 'GEOMETRYN', 'GEOMETRYTYPE', 'GEOMFROMTEXT',
'GEOMETRYFROMTEXT', 'GEOMFROMWKB', 'GEOMETRYFROMWKB', 'GET_FORMAT', 'GET_LOCK', 'GLENGTH', 'GREATEST', 'GROUP_CONCAT',
'GTID_SUBSET', 'GTID_SUBTRACT', 'HEX', 'HOUR', 'IF', 'IFNULL', 'IN', 'INET_ATON', 'INET_NTOA', 'INET6_ATON',
'INET6_NTOA', 'INSERT', 'INSTR', 'INTERIORRINGN', 'INTERSECTS', 'INTERVAL', 'IS_FREE_LOCK', 'IS_IPV4',
'IS_IPV4_COMPAT', 'IS_IPV4_MAPPED', 'IS_IPV6', 'IS_USED_LOCK', 'ISCLOSED', 'ISEMPTY', 'ISNULL', 'ISSIMPLE',
'JSON_APPEND', 'JSON_ARRAY', 'JSON_ARRAY_APPEND', 'JSON_ARRAY_INSERT', 'JSON_CONTAINS', 'JSON_CONTAINS_PATH',
'JSON_DEPTH', 'JSON_EXTRACT', 'JSON_INSERT', 'JSON_KEYS', 'JSON_LENGTH', 'JSON_MERGE', 'JSON_OBJECT', 'JSON_QUOTE',
'JSON_REMOVE', 'JSON_REPLACE', 'JSON_SEARCH', 'JSON_SET', 'JSON_TYPE', 'JSON_UNQUOTE', 'JSON_VALID', 'LAST_DAY',
'LAST_INSERT_ID', 'LCASE', 'LEAST', 'LEFT', 'LENGTH', 'LINEFROMTEXT', 'LINESTRINGFROMTEXT', 'LINEFROMWKB',
'LINESTRINGFROMWKB', 'LINESTRING', 'LN', 'LOAD_FILE', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCATE', 'LOG', 'LOG10', 'LOG2',
'LOWER', 'LPAD', 'LTRIM', 'MAKE_SET', 'MAKEDATE', 'MAKETIME', 'MASTER_POS_WAIT', 'MAX', 'MBRCONTAINS', 'MBRCOVEREDBY',
'MBRCOVERS', 'MBRDISJOINT', 'MBREQUAL', 'MBREQUALS', 'MBRINTERSECTS', 'MBROVERLAPS', 'MBRTOUCHES', 'MBRWITHIN', 'MD5',
'MICROSECOND', 'MID', 'MIN', 'MINUTE', 'MLINEFROMTEXT', 'MULTILINESTRINGFROMTEXT', 'MLINEFROMWKB',
'MULTILINESTRINGFROMWKB', 'MOD', 'MONTH', 'MONTHNAME', 'MPOINTFROMTEXT', 'MULTIPOINTFROMTEXT', 'MPOINTFROMWKB',
'MULTIPOINTFROMWKB', 'MPOLYFROMTEXT', 'MULTIPOLYGONFROMTEXT', 'MPOLYFROMWKB', 'MULTIPOLYGONFROMWKB', 'MULTILINESTRING',
'MULTIPOINT', 'MULTIPOLYGON', 'NAME_CONST', 'NOT IN', 'NOW', 'NULLIF', 'NUMGEOMETRIES', 'NUMINTERIORRINGS',
'NUMPOINTS', 'OCT', 'OCTET_LENGTH', 'OLD_PASSWORD', 'ORD', 'OVERLAPS', 'PASSWORD', 'PERIOD_ADD', 'PERIOD_DIFF', 'PI',
'POINT', 'POINTFROMTEXT', 'POINTFROMWKB', 'POINTN', 'POLYFROMTEXT', 'POLYGONFROMTEXT', 'POLYFROMWKB', 'POLYGONFROMWKB',
'POLYGON', 'POSITION', 'POW', 'POWER', 'PROCEDURE ANALYSE', 'QUARTER', 'QUOTE', 'RADIANS', 'RAND', 'RANDOM_BYTES',
'RELEASE_ALL_LOCKS', 'RELEASE_LOCK', 'REPEAT', 'REPLACE', 'REVERSE', 'RIGHT', 'ROUND', 'ROW_COUNT', 'RPAD', 'RTRIM',
'SCHEMA', 'SEC_TO_TIME', 'SECOND', 'SESSION_USER', 'SHA1', 'SHA', 'SHA2', 'SIGN', 'SIN', 'SLEEP', 'SOUNDEX', 'SPACE',
'SQRT', 'SRID', 'ST_AREA', 'ST_ASBINARY', 'ST_ASWKB', 'ST_ASGEOJSON', 'ST_ASTEXT', 'ST_ASWKT', 'ST_BUFFER',
'ST_BUFFER_STRATEGY', 'ST_CENTROID', 'ST_CONTAINS', 'ST_CONVEXHULL', 'ST_CROSSES', 'ST_DIFFERENCE', 'ST_DIMENSION',
'ST_DISJOINT', 'ST_DISTANCE', 'ST_DISTANCE_SPHERE', 'ST_ENDPOINT', 'ST_ENVELOPE', 'ST_EQUALS', 'ST_EXTERIORRING',
'ST_GEOHASH', 'ST_GEOMCOLLFROMTEXT', 'ST_GEOMETRYCOLLECTIONFROMTEXT', 'ST_GEOMCOLLFROMTXT', 'ST_GEOMCOLLFROMWKB',
'ST_GEOMETRYCOLLECTIONFROMWKB', 'ST_GEOMETRYN', 'ST_GEOMETRYTYPE', 'ST_GEOMFROMGEOJSON', 'ST_GEOMFROMTEXT',
'ST_GEOMETRYFROMTEXT', 'ST_GEOMFROMWKB', 'ST_GEOMETRYFROMWKB', 'ST_INTERIORRINGN', 'ST_INTERSECTION', 'ST_INTERSECTS',
'ST_ISCLOSED', 'ST_ISEMPTY', 'ST_ISSIMPLE', 'ST_ISVALID', 'ST_LATFROMGEOHASH', 'ST_LENGTH', 'ST_LINEFROMTEXT',
'ST_LINESTRINGFROMTEXT', 'ST_LINEFROMWKB', 'ST_LINESTRINGFROMWKB', 'ST_LONGFROMGEOHASH', 'ST_MAKEENVELOPE',
'ST_MLINEFROMTEXT', 'ST_MULTILINESTRINGFROMTEXT', 'ST_MLINEFROMWKB', 'ST_MULTILINESTRINGFROMWKB', 'ST_MPOINTFROMTEXT',
'ST_MULTIPOINTFROMTEXT', 'ST_MPOINTFROMWKB', 'ST_MULTIPOINTFROMWKB', 'ST_MPOLYFROMTEXT', 'ST_MULTIPOLYGONFROMTEXT',
'ST_MPOLYFROMWKB', 'ST_MULTIPOLYGONFROMWKB', 'ST_NUMGEOMETRIES', 'ST_NUMINTERIORRING', 'ST_NUMINTERIORRINGS',
'ST_NUMPOINTS', 'ST_OVERLAPS', 'ST_POINTFROMGEOHASH', 'ST_POINTFROMTEXT', 'ST_POINTFROMWKB', 'ST_POINTN',
'ST_POLYFROMTEXT', 'ST_POLYGONFROMTEXT', 'ST_POLYFROMWKB', 'ST_POLYGONFROMWKB', 'ST_SIMPLIFY', 'ST_SRID',
'ST_STARTPOINT', 'ST_SYMDIFFERENCE', 'ST_TOUCHES', 'ST_UNION', 'ST_VALIDATE', 'ST_WITHIN', 'ST_X', 'ST_Y',
'STARTPOINT', 'STD', 'STDDEV', 'STDDEV_POP', 'STDDEV_SAMP', 'STR_TO_DATE', 'STRCMP', 'SUBDATE', 'SUBSTR', 'SUBSTRING',
'SUBSTRING_INDEX', 'SUBTIME', 'SUM', 'SYSDATE', 'SYSTEM_USER', 'TAN', 'TIME', 'TIME_FORMAT', 'TIME_TO_SEC', 'TIMEDIFF',
'TIMESTAMP', 'TIMESTAMPADD', 'TIMESTAMPDIFF', 'TO_BASE64', 'TO_DAYS', 'TO_SECONDS', 'TOUCHES', 'TRIM', 'TRUNCATE',
'UCASE', 'UNCOMPRESS', 'UNCOMPRESSED_LENGTH', 'UNHEX', 'UNIX_TIMESTAMP', 'UPDATEXML', 'UPPER', 'USER', 'UTC_DATE',
'UTC_TIME', 'UTC_TIMESTAMP', 'UUID', 'UUID_SHORT', 'VALIDATE_PASSWORD_STRENGTH', 'VALUES', 'VAR_POP', 'VAR_SAMP',
'VARIANCE', 'VERSION', 'WAIT_FOR_EXECUTED_GTID_SET', 'WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS', 'WEEK', 'WEEKDAY',
'WEEKOFYEAR', 'WEIGHT_STRING', 'WITHIN', 'X', 'Y', 'YEAR', 'YEARWEEK'
// spell-checker: enable
);
/**
* A flag used for deprecated features (PHP < 5.4.0)
*
* @var boolean
* @access private
*/
private $use_deprecated;
/**
* Constructor of the class
*
* @return void
*/
public function __construct() {
// if the mysqli extension is not loaded, stop execution
if (!extension_loaded('mysqli')) trigger_error('Zebra_Database: mysqli extension is not enabled', E_USER_ERROR);
// get path of class and replace (on a windows machine) \ with /
// this path is to be used for all includes as it is an absolute path
$this->path = preg_replace('/\\\/', '/', dirname(__FILE__));
// sets default values for the class' properties
// public properties
$this->cache_path = rtrim($this->path, '/') . '/cache/';
// let developers know about this feature
$this->debug_show_database_manager = '<a href="https://stefangabos.github.io/Zebra_Database/Zebra_Database/Zebra_Database.html#var$debug_show_database_manager" style="color: #C40000" title="Open in favorite database manager">SET UP</a>';
$this->language($this->language);
// set default warnings:
$this->warnings = array(
'charset' => true, // set_charset not called
'memcache' => true, // memcache is available but it is not used
'redis' => true, // redis is available but it is not used
);
// this is used in the "escape" method
$this->use_deprecated = version_compare(PHP_VERSION, '5.4.0', '<');
// whether the call was made from CLI or from the browser
$this->is_cli_request = strpos(php_sapi_name(), 'cli') === 0;
// show the debug console when script execution ends
register_shutdown_function(array($this, '_show_debugging_console'));
}
/**
* Closes the MySQL connection and optionally unsets the connection options previously set with the {@link option()}
* method
*
* @param boolean $reset_options If set to `TRUE` the library will also unset the connection options previously
* set with the {@link option()} method.
*
* Default is `FALSE`
*
* *This option was added in 2.9.5*
*
* @since 1.1.0
*
* @return boolean Returns `TRUE` on success or `FALSE` on failure
*/
public function close($reset_options = false) {
// close the last open connection, if any
if (!is_bool($this->connection)) $result = mysqli_close($this->connection);
// set this flag to FALSE so that other connection can be opened
$this->connection = false;
// unset previously set credentials
// or otherwise running a query after close will simply reuse those credentials to connect again
$this->credentials = array();
// if options need to be unset, unset them now
if ($reset_options) $this->options = array();
// return the result
return $result;
}
/**
* Opens a connection to a MySQL server and optionally selects a database
*
* Since the library is using *lazy connection* (it is not actually connecting to the database until the first query
* is executed), the object representing the connection to the MySQL server is not available at this time. In case
* you need it before running any queries, use the {@link get_link()} method.
*
* If you want the connection to the database to be made right away, set the `connect` argument to `TRUE`
*
* <code>