forked from stefangabos/Zebra_Database
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZebra_Database.php
4368 lines (3524 loc) · 169 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
/**
* An advanced, compact and lightweight MySQL database wrapper library, built around PHP's
* {@link http://www.php.net/manual/en/book.mysqli.php MySQLi extension}. It provides methods for interacting with MySQL
* databases that are more secure, powerful and intuitive than PHP's default ones.
*
* It supports {@link http://dev.mysql.com/doc/refman/5.0/en/commit.html transactions} and provides ways for caching
* query results either by saving cached data on the disk, or by using {@link http://memcached.org/about memcache}.
*
* Provides a comprehensive debugging interface with detailed information about the executed queries: execution time,
* returned/affected rows, excerpts of the found rows, error messages, etc. It also automatically
* {@link http://dev.mysql.com/doc/refman/5.0/en/explain.html EXPLAIN}'s each SELECT query (so you don't miss those keys
* again!).
*
* It encourages developers to write maintainable code and provides a better default security layer by encouraging the
* use of prepared statements, where arguments are escaped automatically.
*
* The code is heavily commented and generates no warnings/errors/notices when PHP's error reporting level is set to
* E_ALL.
*
* Visit {@link http://stefangabos.ro/php-libraries/zebra-database/} for more information.
*
* For more resources visit {@link http://stefangabos.ro/}
*
* @author Stefan Gabos <[email protected]>
* @version 2.8.5 (last revision: Novemer 12, 2014)
* @copyright (c) 2006 - 2014 Stefan Gabos
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE
* @package Zebra_Database
*/
class Zebra_Database
{
/**
* After an INSERT, UPDATE, REPLACE or DELETE query this property will hold the number of rows that were affected by
* its execution. .
*
* For the number of rows returned by SELECT queries see the {@link $returned_rows} property.
*
* <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;
/**
* Path (with trailing slash) where to cache queries results.
*
* <i>The path must be relative to your working path and not the class' path!</i>
*
* @var string
*/
public $cache_path;
/**
* The method to be used for caching query results.
*
* Can be either:
*
* - <b>disk</b> - query results are cached as files on the disk at the path specified by {@link cache_path}.
* - <b>session</b> - query results are cached in the session (use this only for small data sets). Note that when
* using this method for caching results, the library expects an active session, or will trigger
* a fatal error otherwise!
* - <b>memcache</b> - query results are cached using a {@link http://memcached.org/about memcache} server; when
* using this method make sure to also set the appropriate values for {@link memcache_host},
* {@link memcache_port} and optionally {@link memcache_compressed}.
* <br>
* <i>For using memcache as caching method, PHP must be compiled with the
* {@link http://pecl.php.net/package/memcache memcache} extension and, if {@link memcache_compressed}
* property is set to TRUE, needs to be configured with </i><b>--with-zlib[=DIR]</b><i>.</i>
*
* If caching method is set to "memcache", {@link memcache_host}, {@link memcache_port} and optionally
* {@link memcache_compressed} must be set <b>prior</b> to calling the {@link connect()} method! Failing to do so
* will disable caching.
*
* <code>
* // the host where memcache is listening for connections
* $db->memcache_host = 'localhost';
*
* // the port where 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>
*
* <i>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()}!</i>
*
* Default is "disk".
*
* @since 2.7
*
* @var string
*/
public $caching_method;
/**
* Sets the number records returned by SELECT queries to be shown in the debugging console.
*
* <code>
* // show 50 records
* $db->console_show_records(50);
* </code>
*
* <i>Be aware that having this property set to a high number (hundreds), and having queries that returnthat 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:</i>
*
* <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 $console_show_records;
/**
* Setting this property to TRUE will instruct the library to generate debugging information for each query it executes.
*
* Debugging information can later be reviewed by calling the {@link show_debug_console()} method.
*
* <b>Don't forget to set this to FALSE on the production environment. Generating the debugging information consumes
* a lot of resources and is meant to be used *only* in the development process!</b>.
*
* I recommend always calling the {@link show_debug_console()} method at the end of your scripts, and simply changing
* the value of the <i>debug</i> property to suit your needs, as {@link show_debug_console()} will not display
* anything if <i>debug</i> is FALSE.
*
* Remember that on a production server you will not be left in the dark by setting this property to FALSE, as the
* library will try to write any errors to the system log, if PHP is
* {@link http://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors configured so}!
*
* <code>
* // disable the generation of debugging information
* $db->debug = false;
* </code>
*
* Default is TRUE.
*
* @var boolean
*/
public $debug;
/**
* An array of IP addresses for which, if the {@link debug} property is set to TRUE, the {@link show_debug_console()}
* method should produce output.
*
* An empty array would display the debugging console for everybody.
*
* <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
*/
public $debugger_ip;
/**
* By default, if {@link set_charset()} method is not called, 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 the database.
*
* If you don't want to call this method nor do you want to see the warning, set this property to FALSE.
*
* Default is TRUE.
*
* @var boolean
*/
public $disable_warnings;
/**
* After running a SELECT query through either {@link select()} or {@link query()} methods, and having set the
* <i>calc_rows</i> argument to TRUE, this property would contain the number of records that <b>would</b> have been
* returned <b>if</b> there was no LIMIT applied to the query.
*
* If <i>calc_rows</i> is FALSE or 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.
*
* <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
*/
public $found_rows;
/**
* When the value of this property is set to TRUE, the execution of the script will be halted for any unsuccessful
* query and the debugging console will be shown, <b>if</b> the value of the {@link debug} property is TRUE and the
* viewer's IP address is in the {@link debugger_ip} array (or {@link debugger_ip} is an empty array).
*
* <code>
* // don't stop execution for unsuccessful queries (if possible)
* $db->halt_on_errors = false;
* </code>
*
* Default is TRUE.
*
* @since 1.0.5
*
* @var boolean
*/
public $halt_on_errors;
/**
* Path (with trailing slash) where to store the log file.
*
* <b>The path is relative to your working directory.</b>
*
* Data is written to the log file when calling the {@link write_log()} method.
*
* <i>At the given path the library will attempt to create a file named "log.txt". Remember to grant the appropriate
* rights to the script!</i>
*
* <b>IF YOU'RE LOGGING, MAKE SURE YOU HAVE A CRON JOB OR SOMETHING THAT DELETES THE LOG FILE FROM TIME TO TIME!</b>
*
* Remember that the library will try to write errors to the system log (if PHP is {@link http://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors configured so})
* <b>only</b> when the {@link $debug debug} property is set to FALSE (as when the <i>debug</i> property is set to
* TRUE the error messages are reported in the debugging console);
*
* @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;
/**
* Setting this property to TRUE will instruct to library to compress (using zlib) the cached results.
*
* <i>For this to work, PHP needs to be configured with </i> <b>--with-zlib[=DIR]</b> <i>!</i>
*
* <i>Set this property only if you are using "memcache" as {@link caching_method}.</i>
*
* Default is FALSE.
*
* @since 2.7
*
* @var boolean
*/
public $memcache_compressed;
/**
* The host where memcache is listening for connections.
*
* <i>Set this property only if you are using "memcache" as {@link caching_method}.</i>
*
* Default is FALSE.
*
* @since 2.7
*
* @var mixed
*/
public $memcache_host;
/**
* The port where memcache is listening for connections.
*
* <i>Set this property only if you are using "memcache" as {@link caching_method}.</i>
*
* Default is FALSE.
*
* @since 2.7
*
* @var mixed
*/
public $memcache_port;
/**
* The prefix for the keys used to identify cached queries in memcache. This allows sepparate caching of the same
* queries by multiple instances of the libraries, or the same instance handling multiple domains on the same
* memcache server.
*
* <i>Set this property only if you are using "memcache" as {@link caching_method}.</i>
*
* Default is "" (an empty string).
*
* @since 2.8.4
*
* @var string
*/
public $memcache_key_prefix;
/**
* 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 <i>highlight</i> 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;
/**
* 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.
*
* <code>
* // the email address where to send an email when there are slow queries
* $db->notification_address = '[email protected]';
* </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.
*
* <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;
/**
* After running a SELECT query through either {@link select()} or {@link query()} methods this property would
* contain the number of returned rows.
*
* 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;
/**
* Path (without leading slash) to parent of public folder containing the css and javascript folders.
*
* <i>The path must be relative to your $_SERVER['DOCUMENT_ROOT'] and not the class' path!</i>
*
* @var string
*/
public $resource_path;
/**
* Array with cached results.
*
* We will use this for fetching and seek
*
* @access private
*/
private $cached_results;
/**
* Array that will store the database connection credentials
*
* @access private
*/
private $credentials;
/**
* All debugging information is stored in this array.
*
* @access private
*/
private $debug_info;
/**
* The language to be used in the debugging console.
*
* Default is "english".
*
* @access private
*/
private $language;
/**
* MySQL link identifier.
*
* @access private
*/
private $connection;
/**
* Instance of an opened memcache server connection.
*
* @since 2.7
*
* @access private
*/
private $memcache;
/**
* 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
*
* @access private
*/
private $transaction_status;
/**
* Array of warnings, generated by the script, to be shown to the user in the debugging console
*
* @access private
*/
private $warnings;
/**
* Constructor of the class
*
* @return void
*/
function __construct()
{
// if the mysqli extension is not loded, 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 = $this->path . '/cache/';
$this->console_show_records = 20;
$this->debug = $this->halt_on_errors = $this->minimize_console = true;
$this->language('english');
$this->max_query_time = 10;
$this->log_path = $this->notification_address = $this->notifier_domain = $this->memcache_key_prefix = '';
$this->total_execution_time = $this->transaction_status = 0;
$this->caching_method = 'disk';
$this->cached_results = $this->debug_info = $this->debugger_ip = array();
$this->connection = $this->memcache = $this->memcache_host = $this->memcache_port = $this->memcache_compressed = false;
// set default warnings:
$this->warnings = array(
'charset' => true, // set_charset not called
'memcache' => true, // memcache is available but it is not used
);
}
/**
* Closes the MySQL connection.
*
* @since 1.1.0
*
* @return boolean Returns TRUE on success or FALSE on failure.
*/
function close()
{
// close the last one open
return @mysqli_close($this->connection);
}
/**
* Opens a connection to a MySQL Server and selects a database.
*
* Since the library is using <i>lazy connection</i> (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. If
* you need it, use the {@link get_link()} method.
*
* If you need the connection to the database to be made right away, set the <i>connect</i> argument to TRUE.
*
* <code>
* // create the database object
* $db = new Zebra_Database();
*
* // notice that we're not doing any error checking. errors will be shown in the debugging console
* $db->connect('host', 'username', 'password', 'database');
*
* // code goes here
*
* // show the debugging console (if enabled)
* $db->show_debug_console();
* </code>
*
* @param string $host The address of the MySQL server to connect to (i.e. localhost).
*
* Prepending host by <b>p:</b> opens a persistent connection.
*
* @param string $user The user name used for authentication when connecting to the MySQL server.
*
* @param string $password The password used for authentication when connecting to the MySQL server.
*
* @param string $database The database to be selected after the connection is established.
*
* @param string $port (Optional) The port number to attempt to connect to the MySQL server.
*
* Leave as empty string to use the default as returned by ini_get("mysqli.default_port").
*
* @param string $socket (Optional) The socket or named pipe that should be used.
*
* Leave as empty string to use the default as returned by ini_get("mysqli.default_socket").
*
* Specifying the socket parameter will not explicitly determine the type of connection
* to be used when connecting to the MySQL server. How the connection is made to the MySQL
* database is determined by the <i>host</i> argument.
*
* @param boolean $connect (Optional) Setting this argument to TRUE will force the library to connect to the
* database right away instead of using a "lazy connection" where the actual connection
* to the database will be made when the first query is run.
*
* Default is FALSE.
*
* @return void
*/
function connect($host, $user, $password, $database, $port = '', $socket = '', $connect = false)
{
// if the "memcache" extension is loaded and the caching method is set to "memcache"
if (extension_loaded('memcache') && $this->caching_method == 'memcache')
// suppress the warning telling the developer to use memcache for caching query results
unset($this->warnings['memcache']);
// we are using lazy-connection
// that is, we are not going to actually connect to the database until we execute the first query
// the actual connection is done by the _connected method
$this->credentials = array(
'host' => $host,
'user' => $user,
'password' => $password,
'database' => $database,
'port' => $port == '' ? ini_get('mysqli.default_port') : $port,
'socket' => $socket == '' ? ini_get('mysqli.default_socket') : $socket,
);
// connect now, if we need to connect right away
if ($connect) $this->_connected();
}
/**
* Counts the values in a column of a table.
*
* <code>
* // count male users
* $male = $db->dcount('id', 'users', 'gender = "M"');
*
* // when working with variables you should use the following syntax
* // this way you will stay clear of SQL injections
* $users = $db->dcount('id', 'users', 'gender = ?', array($gender));
* </code>
*
* @param string $column Name of the column in which to do the counting.
*
* @param string $table Name of the table containing the column.
*
* @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword).
*
* Default is "" (an empty string).
*
* @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question
* marks) in <i>$column</i>, <i>$table</i> and <i>$where</i>. Each item will be
* automatically {@link escape()}-ed and will replace the corresponding "?".
*
* Default is "" (an empty string).
*
* @param mixed $cache (Optional) Instructs the library on whether it should cache the query's results
* or not. Can be either FALSE - meaning no caching - or an integer representing the
* number of seconds after which the cache will be considered expired and the query
* executed again.
*
* The caching method is specified by the value of the {@link caching_method} property.
*
* Default is FALSE.
*
* @param boolean $highlight (Optional) If set to TRUE the debugging console will be opened automatically
* and the query will be shown - really useful for quick and easy debugging.
*
* Default is FALSE.
*
* @return mixed Returns the number of counted records or FALSE if no records matching the given
* criteria (if any) were found. It also returns FALSE if there are no records in
* the table or if there was an error.
*
* <i>This method may return boolean FALSE but may also return a non-boolean value
* which evaluates to FALSE, such as 0. Use the === operator for testing the return
* value of this method.</i>
*/
function dcount($column, $table, $where = '', $replacements = '', $cache = false, $highlight = false)
{
// run the query
$this->query('
SELECT
COUNT(' . $column . ') AS counted
FROM
`'. $table . '`' .
($where != '' ? ' WHERE ' . $where : '')
, $replacements, $cache, false, $highlight);
// if query was executed successfully and one or more records were returned
if ($this->last_result !== false && $this->returned_rows > 0) {
// fetch the result
$row = $this->fetch_assoc();
// return the result
return $row['counted'];
}
// if error or no records
return false;
}
/**
* Deletes rows from a table.
*
* <code>
* // delete male users
* $db->delete('users', 'gender = "M"');
*
* // when working with variables you should use the following syntax
* // this way you will stay clear of SQL injections
* $db->delete('users', 'gender = ?', array($gender));
* </code>
*
* @param string $table Table from which to delete.
*
* @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword).
*
* Default is "" (an empty string).
*
* @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question
* marks) in <i>$table</i> and <i>$where</i>. Each item will be automatically
* {@link escape()}-ed and will replace the corresponding "?".
*
* Default is "" (an empty string).
*
* @param boolean $highlight (Optional) If set to TRUE the debugging console will be opened automatically
* and the query will be shown - really useful for quick and easy debugging.
*
* Default is FALSE.
*
* @since 1.0.9
*
* @return boolean Returns TRUE on success or FALSE on error.
*/
function delete($table, $where = '', $replacements = '', $highlight = false)
{
// run the query
$this->query('
DELETE FROM
`'. $table . '`' .
($where != '' ? ' WHERE ' . $where : '')
, $replacements, false, false, $highlight);
// if query was successful
if ($this->last_result) return true;
// if query was unsuccessful
return false;
}
/**
* Returns one or more columns from ONE row of a table.
*
* <code>
* // get name, surname and age of all male users
* $result = $db->dlookup('name, surname, age', 'users', 'gender = "M"');
*
* // when working with variables you should use the following syntax
* // this way you will stay clear of SQL injections
* $result = $db->dlookup('name, surname, age', 'users', 'gender = ?', array($gender));
* </code>
*
* @param string $column One or more columns to return data from.
*
* <i>If only one column is specified the returned result will be the specified
* column's value. If more columns are specified the returned result will be an
* associative array!</i>
*
* <i>You may use "*" (without the quotes) to return all the columns from the
* row.</i>
*
* @param string $table Name of the table in which to search.
*
* @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword).
*
* Default is "" (an empty string).
*
* @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question
* marks) in <i>$column</i>, <i>$table</i> and <i>$where</i>. Each item will be
* automatically {@link escape()}-ed and will replace the corresponding "?".
*
* Default is "" (an empty string).
*
* @param mixed $cache (Optional) Instructs the library on whether it should cache the query's results
* or not. Can be either FALSE - meaning no caching - or an integer representing the
* number of seconds after which the cache will be considered expired and the query
* executed again.
*
* The caching method is specified by the value of the {@link caching_method} property.
*
* Default is FALSE.
*
* @param boolean $highlight (Optional) If set to TRUE the debugging console will be opened automatically
* and the query will be shown - really useful for quick and easy debugging.
*
* Default is FALSE.
*
* @return mixed Found value/values or FALSE if no records matching the given criteria (if any)
* were found. It also returns FALSE if there are no records in the table or if there
* was an error.
*/
function dlookup($column, $table, $where = '', $replacements = '', $cache = false, $highlight = false)
{
// run the query
$this->query('
SELECT
' . $column . '
FROM
`'. $table . '`' .
($where != '' ? ' WHERE ' . $where : '') . '
LIMIT 1
', $replacements, $cache, false, $highlight);
// if query was executed successfully and one or more records were returned
if ($this->last_result !== false && $this->returned_rows > 0) {
// fetch the result
$row = $this->fetch_assoc();
// if there is only one column in the returned set
// return as a single value
if (count($row) == 1) return array_pop($row);
// if more than one columns, return as an array
else return $row;
}
// if error or no records
return false;
}
/**
* Looks up the maximum value in a column of a table.
*
* <code>
* // get the maximum age of male users
* $result = $db->dmax('age', 'users', 'gender = "M"');
*
* // when working with variables you should use the following syntax
* // this way you will stay clear of SQL injections
* $result = $db->dmax('age', 'users', 'gender = ?', array($gender));
* </code>
*
* @param string $column Name of the column in which to search.
*
* @param string $table Name of table in which to search.
*
* @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword).
*
* Default is "" (an empty string).
*
* @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question
* marks) in <i>$column</i>, <i>$table</i> and <i>$where</i>. Each item will be
* automatically {@link escape()}-ed and will replace the corresponding "?".
*
* Default is "" (an empty string).
*
* @param mixed $cache (Optional) Instructs the library on whether it should cache the query's results
* or not. Can be either FALSE - meaning no caching - or an integer representing the
* number of seconds after which the cache will be considered expired and the query
* executed again.
*
* The caching method is specified by the value of the {@link caching_method} property.
*
* Default is FALSE.
*
* @param boolean $highlight (Optional) If set to TRUE the debugging console will be opened automatically
* and the query will be shown - really useful for quick and easy debugging.
*
* Default is FALSE.
*
* @return mixed The maximum value in the column or FALSE if no records matching the given criteria
* (if any) were found. It also returns FALSE if there are no records in the table
* or if there was an error.
*
* <i>This method may return boolean FALSE but may also return a non-boolean value
* which evaluates to FALSE, such as 0. Use the === operator for testing the return
* value of this method.</i>
*/
function dmax($column, $table, $where = '', $replacements = '', $cache = false, $highlight = false)
{
// run the query
$this->query('
SELECT
MAX(' . $column . ') AS maximum
FROM
`'. $table . '`' .
($where != '' ? ' WHERE ' . $where : '')
, $replacements, $cache, false, $highlight);
// if query was executed successfully and one or more records were returned
if ($this->last_result !== false && $this->returned_rows > 0) {
// fetch the result
$row = $this->fetch_assoc();
// return the result
return $row['maximum'];
}
// if error or no records
return false;
}
/**
* Sums the values in a column of a table.
*
* Example:
*
* <code>
* // get the total logins of all male users
* $result = $db->dsum('login_count', 'users', 'gender = "M"');
*
* // when working with variables you should use the following syntax
* // this way you will stay clear of SQL injections
* $result = $db->dsum('login_count', 'users', 'gender = ?', array($gender));
* </code>
*
* @param string $column Name of the column in which to sum values.
*
* @param string $table Name of the table in which to search.
*
* @param string $where (Optional) A MySQL WHERE clause (without the WHERE keyword).
*
* Default is "" (an empty string).
*
* @param array $replacements (Optional) An array with as many items as the total parameter markers ("?", question
* marks) in <i>$column</i>, <i>$table</i> and <i>$where</i>. Each item will be
* automatically {@link escape()}-ed and will replace the corresponding "?".
*
* Default is "" (an empty string).
*
* @param mixed $cache (Optional) Instructs the library on whether it should cache the query's results
* or not. Can be either FALSE - meaning no caching - or an integer representing the
* number of seconds after which the cache will be considered expired and the query
* executed again.
*
* The caching method is specified by the value of the {@link caching_method} property.
*
* Default is FALSE.
*
* @param boolean $highlight (Optional) If set to TRUE the debugging console will be opened automatically
* and the query will be shown - really useful for quick and easy debugging.
*
* Default is FALSE.
*
* @return mixed Returns the sum, or FALSE if no records matching the given criteria (if any) were
* found. It also returns FALSE if there are no records in the table or on error.
*
* <i>This method may return boolean FALSE but may also return a non-boolean value
* which evaluates to FALSE, such as 0. Use the === operator for testing the return
* value of this method.</i>
*/
function dsum($column, $table, $where = '', $replacements = '', $cache = false, $highlight = false)
{
// run the query
$this->query('
SELECT
SUM(' . $column . ') AS total
FROM
`'. $table . '`' .
($where != '' ? ' WHERE ' . $where : '')