-
Notifications
You must be signed in to change notification settings - Fork 60
/
class.db.php
931 lines (843 loc) · 23.7 KB
/
class.db.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
<?php
/*------------------------------------------------------------------------------
** File: class.db.php
** Class: Simply MySQLi
** Description: PHP MySQLi wrapper class to handle common database queries and operations
** Version: 2.1.4
** Updated: 11-Sep-2014
** Author: Bennett Stone
** Homepage: www.phpdevtips.com
**------------------------------------------------------------------------------
** COPYRIGHT (c) 2012 - 2014 BENNETT STONE
**
** The source code included in this package is free software; you can
** redistribute it and/or modify it under the terms of the GNU General Public
** License as published by the Free Software Foundation. This license can be
** read at:
**
** http://www.opensource.org/licenses/gpl-license.php
**
** This program is distributed in the hope that it will be useful, but WITHOUT
** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
** FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
**------------------------------------------------------------------------------ */
/*******************************
Example initialization:
define( 'DB_HOST', 'localhost' ); // set database host
define( 'DB_USER', 'root' ); // set database user
define( 'DB_PASS', 'root' ); // set database password
define( 'DB_NAME', 'yourdatabasename' ); // set database name
define( 'SEND_ERRORS_TO', 'you@yourwebsite.com' ); //set email notification email address
define( 'DISPLAY_DEBUG', true ); //display db errors?
require_once( 'class.db.php' );
//Initiate the class
$database = new DB();
//OR...
$database = DB::getInstance();
NOTE:
All examples provided below assume that this class has been initiated
Examples below assume the class has been iniated using $database = DB::getInstance();
********************************/
class DB
{
private $link = null;
public $filter;
static $inst = null;
public static $counter = 0;
/**
* Allow the class to send admins a message alerting them to errors
* on production sites
*
* @access public
* @param string $error
* @param string $query
* @return mixed
*/
public function log_db_errors( $error, $query )
{
$message = '<p>Error at '. date('Y-m-d H:i:s').':</p>';
$message .= '<p>Query: '. htmlentities( $query ).'<br />';
$message .= 'Error: ' . $error;
$message .= '</p>';
if( defined( 'SEND_ERRORS_TO' ) )
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: Admin <'.SEND_ERRORS_TO.'>' . "\r\n";
$headers .= 'From: Yoursite <system@'.$_SERVER['SERVER_NAME'].'.com>' . "\r\n";
mail( SEND_ERRORS_TO, 'Database Error', $message, $headers );
}
else
{
trigger_error( $message );
}
if( !defined( 'DISPLAY_DEBUG' ) || ( defined( 'DISPLAY_DEBUG' ) && DISPLAY_DEBUG ) )
{
echo $message;
}
}
public function __construct()
{
mb_internal_encoding( 'UTF-8' );
mb_regex_encoding( 'UTF-8' );
mysqli_report( MYSQLI_REPORT_STRICT );
try {
$this->link = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME );
$this->link->set_charset( "utf8" );
} catch ( Exception $e ) {
die( 'Unable to connect to database' );
}
}
public function __destruct()
{
if( $this->link)
{
$this->disconnect();
}
}
/**
* Sanitize user data
*
* Example usage:
* $user_name = $database->filter( $_POST['user_name'] );
*
* Or to filter an entire array:
* $data = array( 'name' => $_POST['name'], 'email' => 'email@address.com' );
* $data = $database->filter( $data );
*
* @access public
* @param mixed $data
* @return mixed $data
*/
public function filter( $data )
{
if( !is_array( $data ) )
{
$data = $this->link->real_escape_string( $data );
$data = trim( htmlentities( $data, ENT_QUOTES, 'UTF-8', false ) );
}
else
{
//Self call function to sanitize array data
$data = array_map( array( $this, 'filter' ), $data );
}
return $data;
}
/**
* Extra function to filter when only mysqli_real_escape_string is needed
* @access public
* @param mixed $data
* @return mixed $data
*/
public function escape( $data )
{
if( !is_array( $data ) )
{
$data = $this->link->real_escape_string( $data );
}
else
{
//Self call function to sanitize array data
$data = array_map( array( $this, 'escape' ), $data );
}
return $data;
}
/**
* Normalize sanitized data for display (reverse $database->filter cleaning)
*
* Example usage:
* echo $database->clean( $data_from_database );
*
* @access public
* @param string $data
* @return string $data
*/
public function clean( $data )
{
$data = stripslashes( $data );
$data = html_entity_decode( $data, ENT_QUOTES, 'UTF-8' );
$data = nl2br( $data );
$data = urldecode( $data );
return $data;
}
/**
* Determine if common non-encapsulated fields are being used
*
* Example usage:
* if( $database->db_common( $query ) )
* {
* //Do something
* }
* Used by function exists
*
* @access public
* @param string
* @param array
* @return bool
*
*/
public function db_common( $value = '' )
{
if( is_array( $value ) )
{
foreach( $value as $v )
{
if( preg_match( '/AES_DECRYPT/i', $v ) || preg_match( '/AES_ENCRYPT/i', $v ) || preg_match( '/now()/i', $v ) )
{
return true;
}
else
{
return false;
}
}
}
else
{
if( preg_match( '/AES_DECRYPT/i', $value ) || preg_match( '/AES_ENCRYPT/i', $value ) || preg_match( '/now()/i', $value ) )
{
return true;
}
}
}
/**
* Perform queries
* All following functions run through this function
*
* @access public
* @param string
* @return string
* @return array
* @return bool
*
*/
public function query( $query )
{
$full_query = $this->link->query( $query );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $query );
return false;
}
else
{
return true;
}
}
/**
* Determine if database table exists
* Example usage:
* if( !$database->table_exists( 'checkingfortable' ) )
* {
* //Install your table or throw error
* }
*
* @access public
* @param string
* @return bool
*
*/
public function table_exists( $name )
{
self::$counter++;
$check = $this->link->query( "SELECT 1 FROM $name" );
if($check !== false)
{
if( $check->num_rows > 0 )
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
/**
* Count number of rows found matching a specific query
*
* Example usage:
* $rows = $database->num_rows( "SELECT id FROM users WHERE user_id = 44" );
*
* @access public
* @param string
* @return int
*
*/
public function num_rows( $query )
{
self::$counter++;
$num_rows = $this->link->query( $query );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $query );
return $this->link->error;
}
else
{
return $num_rows->num_rows;
}
}
/**
* Run check to see if value exists, returns true or false
*
* Example Usage:
* $check_user = array(
* 'user_email' => 'someuser@gmail.com',
* 'user_id' => 48
* );
* $exists = $database->exists( 'your_table', 'user_id', $check_user );
*
* @access public
* @param string database table name
* @param string field to check (i.e. 'user_id' or COUNT(user_id))
* @param array column name => column value to match
* @return bool
*
*/
public function exists( $table = '', $check_val = '', $params = array() )
{
self::$counter++;
if( empty($table) || empty($check_val) || empty($params) )
{
return false;
}
$check = array();
foreach( $params as $field => $value )
{
if( !empty( $field ) && !empty( $value ) )
{
//Check for frequently used mysql commands and prevent encapsulation of them
if( $this->db_common( $value ) )
{
$check[] = "$field = $value";
}
else
{
$check[] = "$field = '$value'";
}
}
}
$check = implode(' AND ', $check);
$rs_check = "SELECT $check_val FROM ".$table." WHERE $check";
$number = $this->num_rows( $rs_check );
if( $number === 0 )
{
return false;
}
else
{
return true;
}
}
/**
* Return specific row based on db query
*
* Example usage:
* list( $name, $email ) = $database->get_row( "SELECT name, email FROM users WHERE user_id = 44" );
*
* @access public
* @param string
* @param bool $object (true returns results as objects)
* @return array
*
*/
public function get_row( $query, $object = false )
{
self::$counter++;
$row = $this->link->query( $query );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $query );
return false;
}
else
{
$r = ( !$object ) ? $row->fetch_row() : $row->fetch_object();
return $r;
}
}
/**
* Perform query to retrieve array of associated results
*
* Example usage:
* $users = $database->get_results( "SELECT name, email FROM users ORDER BY name ASC" );
* foreach( $users as $user )
* {
* echo $user['name'] . ': '. $user['email'] .'<br />';
* }
*
* @access public
* @param string
* @param bool $object (true returns object)
* @return array
*
*/
public function get_results( $query, $object = false )
{
self::$counter++;
//Overwrite the $row var to null
$row = null;
$results = $this->link->query( $query );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $query );
return false;
}
else
{
$row = array();
while( $r = ( !$object ) ? $results->fetch_assoc() : $results->fetch_object() )
{
$row[] = $r;
}
return $row;
}
}
/**
* Insert data into database table
*
* Example usage:
* $user_data = array(
* 'name' => 'Bennett',
* 'email' => 'email@address.com',
* 'active' => 1
* );
* $database->insert( 'users_table', $user_data );
*
* @access public
* @param string table name
* @param array table column => column value
* @return bool
*
*/
public function insert( $table, $variables = array() )
{
self::$counter++;
//Make sure the array isn't empty
if( empty( $variables ) )
{
return false;
}
$sql = "INSERT INTO ". $table;
$fields = array();
$values = array();
foreach( $variables as $field => $value )
{
$fields[] = $field;
$values[] = "'".$value."'";
}
$fields = ' (' . implode(', ', $fields) . ')';
$values = '('. implode(', ', $values) .')';
$sql .= $fields .' VALUES '. $values;
$query = $this->link->query( $sql );
if( $this->link->error )
{
//return false;
$this->log_db_errors( $this->link->error, $sql );
return false;
}
else
{
return true;
}
}
/**
* Insert data KNOWN TO BE SECURE into database table
* Ensure that this function is only used with safe data
* No class-side sanitizing is performed on values found to contain common sql commands
* As dictated by the db_common function
* All fields are assumed to be properly encapsulated before initiating this function
*
* @access public
* @param string table name
* @param array table column => column value
* @return bool
*/
public function insert_safe( $table, $variables = array() )
{
self::$counter++;
//Make sure the array isn't empty
if( empty( $variables ) )
{
return false;
}
$sql = "INSERT INTO ". $table;
$fields = array();
$values = array();
foreach( $variables as $field => $value )
{
$fields[] = $this->filter( $field );
//Check for frequently used mysql commands and prevent encapsulation of them
$values[] = $value;
}
$fields = ' (' . implode(', ', $fields) . ')';
$values = '('. implode(', ', $values) .')';
$sql .= $fields .' VALUES '. $values;
$query = $this->link->query( $sql );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $sql );
return false;
}
else
{
return true;
}
}
/**
* Insert multiple records in a single query into a database table
*
* Example usage:
* $fields = array(
* 'name',
* 'email',
* 'active'
* );
* $records = array(
* array(
* 'Bennett', 'bennett@email.com', 1
* ),
* array(
* 'Lori', 'lori@email.com', 0
* ),
* array(
* 'Nick', 'nick@nick.com', 1, 'This will not be added'
* ),
* array(
* 'Meghan', 'meghan@email.com', 1
* )
* );
* $database->insert_multi( 'users_table', $fields, $records );
*
* @access public
* @param string table name
* @param array table columns
* @param nested array records
* @return bool
* @return int number of records inserted
*
*/
public function insert_multi( $table, $columns = array(), $records = array() )
{
self::$counter++;
//Make sure the arrays aren't empty
if( empty( $columns ) || empty( $records ) )
{
return false;
}
//Count the number of fields to ensure insertion statements do not exceed the same num
$number_columns = count( $columns );
//Start a counter for the rows
$added = 0;
//Start the query
$sql = "INSERT INTO ". $table;
$fields = array();
//Loop through the columns for insertion preparation
foreach( $columns as $field )
{
$fields[] = '`'.$field.'`';
}
$fields = ' (' . implode(', ', $fields) . ')';
//Loop through the records to insert
$values = array();
foreach( $records as $record )
{
//Only add a record if the values match the number of columns
if( count( $record ) == $number_columns )
{
$values[] = '(\''. implode( '\', \'', array_values( $record ) ) .'\')';
$added++;
}
}
$values = implode( ', ', $values );
$sql .= $fields .' VALUES '. $values;
$query = $this->link->query( $sql );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $sql );
return false;
}
else
{
return $added;
}
}
/**
* Update data in database table
*
* Example usage:
* $update = array( 'name' => 'Not bennett', 'email' => 'someotheremail@email.com' );
* $update_where = array( 'user_id' => 44, 'name' => 'Bennett' );
* $database->update( 'users_table', $update, $update_where, 1 );
*
* @access public
* @param string table name
* @param array values to update table column => column value
* @param array where parameters table column => column value
* @param int limit
* @return bool
*
*/
public function update( $table, $variables = array(), $where = array(), $limit = '' )
{
self::$counter++;
//Make sure the required data is passed before continuing
//This does not include the $where variable as (though infrequently)
//queries are designated to update entire tables
if( empty( $variables ) )
{
return false;
}
$sql = "UPDATE ". $table ." SET ";
foreach( $variables as $field => $value )
{
$updates[] = "`$field` = '$value'";
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if( !empty( $where ) )
{
foreach( $where as $field => $value )
{
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if( !empty( $limit ) )
{
$sql .= ' LIMIT '. $limit;
}
$query = $this->link->query( $sql );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $sql );
return false;
}
else
{
return true;
}
}
/**
* Delete data from table
*
* Example usage:
* $where = array( 'user_id' => 44, 'email' => 'someotheremail@email.com' );
* $database->delete( 'users_table', $where, 1 );
*
* @access public
* @param string table name
* @param array where parameters table column => column value
* @param int max number of rows to remove.
* @return bool
*
*/
public function delete( $table, $where = array(), $limit = '' )
{
self::$counter++;
//Delete clauses require a where param, otherwise use "truncate"
if( empty( $where ) )
{
return false;
}
$sql = "DELETE FROM ". $table;
foreach( $where as $field => $value )
{
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= " WHERE ". implode(' AND ', $clause);
if( !empty( $limit ) )
{
$sql .= " LIMIT ". $limit;
}
$query = $this->link->query( $sql );
if( $this->link->error )
{
//return false; //
$this->log_db_errors( $this->link->error, $sql );
return false;
}
else
{
return true;
}
}
/**
* Get last auto-incrementing ID associated with an insertion
*
* Example usage:
* $database->insert( 'users_table', $user );
* $last = $database->lastid();
*
* @access public
* @param none
* @return int
*
*/
public function lastid()
{
self::$counter++;
return $this->link->insert_id;
}
/**
* Return the number of rows affected by a given query
*
* Example usage:
* $database->insert( 'users_table', $user );
* $database->affected();
*
* @access public
* @param none
* @return int
*/
public function affected()
{
return $this->link->affected_rows;
}
/**
* Get number of fields
*
* Example usage:
* echo $database->num_fields( "SELECT * FROM users_table" );
*
* @access public
* @param query
* @return int
*/
public function num_fields( $query )
{
self::$counter++;
$query = $this->link->query( $query );
$fields = $query->field_count;
return $fields;
}
/**
* Get field names associated with a table
*
* Example usage:
* $fields = $database->list_fields( "SELECT * FROM users_table" );
* echo '<pre>';
* print_r( $fields );
* echo '</pre>';
*
* @access public
* @param query
* @return array
*/
public function list_fields( $query )
{
self::$counter++;
$query = $this->link->query( $query );
$listed_fields = $query->fetch_fields();
return $listed_fields;
}
/**
* Truncate entire tables
*
* Example usage:
* $remove_tables = array( 'users_table', 'user_data' );
* echo $database->truncate( $remove_tables );
*
* @access public
* @param array database table names
* @return int number of tables truncated
*
*/
public function truncate( $tables = array() )
{
if( !empty( $tables ) )
{
$truncated = 0;
foreach( $tables as $table )
{
$truncate = "TRUNCATE TABLE `".trim($table)."`";
$this->link->query( $truncate );
if( !$this->link->error )
{
$truncated++;
self::$counter++;
}
}
return $truncated;
}
}
/**
* Output results of queries
*
* @access public
* @param string variable
* @param bool echo [true,false] defaults to true
* @return string
*
*/
public function display( $variable, $echo = true )
{
$out = '';
if( !is_array( $variable ) )
{
$out .= $variable;
}
else
{
$out .= '<pre>';
$out .= print_r( $variable, TRUE );
$out .= '</pre>';
}
if( $echo === true )
{
echo $out;
}
else
{
return $out;
}
}
/**
* Output the total number of queries
* Generally designed to be used at the bottom of a page after
* scripts have been run and initialized as needed
*
* Example usage:
* echo 'There were '. $database->total_queries() . ' performed';
*
* @access public
* @param none
* @return int
*/
public function total_queries()
{
return self::$counter;
}
/**
* Singleton function
*
* Example usage:
* $database = DB::getInstance();
*
* @access private
* @return self
*/
static function getInstance()
{
if( self::$inst == null )
{
self::$inst = new DB();
}
return self::$inst;
}
/**
* Disconnect from db server
* Called automatically from __destruct function
*/
public function disconnect()
{
$this->link->close();
}
} //end class DB