-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMySQL_wrapper.class.php
1486 lines (1358 loc) · 50.6 KB
/
MySQL_wrapper.class.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
/******************************************************************
*
* Projectname: PHP MySQL Wrapper Class
* Version: 1.6.1
* Author: Radovan Janjic <[email protected]>
* Link: https://github.com/uzi88/PHP_MySQL_wrapper
* Last modified: 29 10 2014
* Copyright (C): 2008-2014 IT-radionica.com, All Rights Reserved
*
* GNU General Public License (Version 2, June 1991)
*
* This program 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; either version 2 of the License,
* or (at your option) any later version.
*
* 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.
*
******************************************************************/
/** Execute MySQL queries defined programmatically.
* @param string $server - MySQL Host name or ( host:port )
* @param string $username - MySQL User
* @param string $password - MySQL Password
* @param string $database - MySQL Database
*/
class MySQL_wrapper {
/** Class Version
* @var float
*/
private $version = '1.6.2';
/** Store the single instance
* @var array
*/
private static $instance = array();
/** MySQL Host name
* @var string
*/
private $server = NULL;
/** MySQL User
* @var string
*/
private $username = NULL;
/** MySQL Password
* @var string
*/
private $password = NULL;
/** MySQL Database
* @var string
*/
private $database = NULL;
/** mysql / mysqli
* @var string
*/
public $extension = 'mysqli';
/** Connection Charset (Default: UTF-8)
* @var string
*/
public $charset = 'utf8';
/** Error Description
* @var string
* */
public $error = NULL;
/** Error Number
* @var integer
*/
public $errorNo = 0;
/** Display Errors (Default: TRUE)
* @var boolean
*/
public $displayError = TRUE;
/** Link
* @var resource
*/
public $link = 0;
/** Query
* @var resource
*/
public $query = 0;
/** Affected Rows
* @var integer
*/
public $affected = 0;
/** Previous query
* @var string
*/
public $prevQuery = NULL;
/** Log Queries to file (Default: FALSE)
* @var boolean
*/
public $logQueries = FALSE;
/** Log Errors to file (Default: FALSE)
* @var boolean
*/
public $logErrors = FALSE;
/** Stop script execution on error (Default: FALSE)
* @var boolean
*/
public $dieOnError = FALSE;
/** E-mail errors (Default: FALSE)
* @var boolean
*/
public $emailErrors = FALSE;
/** E-mail errors to (array with emails)
* @var array
*/
public $emailErrorsTo = array();
/** E-mail errors subject
* @var string
*/
public $emailErrorsSubject = 'MySQL ERROR ON SERVER: %s';
/** Log Date Format (Default: Y-m-d H:i:s)
* @var string
*/
public $dateFormat = 'Y-m-d H:i:s';
/** Log File Path (Default: log-mysql.txt)
* @var string
*/
public $logFilePath = 'log-mysql.txt';
/** Reserved words for array to ( insert / update )
* @var array
*/
public $reserved = array('null', 'now()', 'current_timestamp', 'curtime()', 'localtime()', 'localtime', 'utc_date()', 'utc_time()', 'utc_timestamp()');
/** Start of MySQL statement for array to ( insert / update )
* @var string
*/
public $statementStart = 'sql::';
/** REGEX
* @var array
*/
private $REGEX = array('LIMIT' => '/limit[\s]+([\d]+[\s]*,[\s]*[\d]+[\s]*|[\d]+[\s]*)$/i', 'COLUMN' => '/^[a-z0-9_\-\s]+$/i');
/** Use MySQL SELECT ... INTO OUTFILE (Default: TRUE)
* @var boolean
*/
private $attachment = FALSE;
/** Use MySQL SELECT ... INTO OUTFILE (Default: TRUE)
* @var boolean
*/
public $mysqlOutFile = TRUE;
/** Singleton declaration
* @param string $server - MySQL Host name
* @param string $username - MySQL User
* @param string $password - MySQL Password
* @param string $database - MySQL Database
* @return - singleton instance
*/
public static function getInstance($server = NULL, $username = NULL, $password = NULL, $database = NULL) {
$md5 = md5(implode('|', array($server, $username, $password, $database)));
if (empty(self::$instance[$md5])) {
self::$instance[$md5] = new MySQL_wrapper($server, $username, $password, $database);
}
return self::$instance[$md5];
}
/** Protected constructor to prevent creating a new instance of the MySQL_wrapper via the `new` operator from outside of this class.
* @param string $server - MySQL Host name
* @param string $username - MySQL User
* @param string $password - MySQL Password
* @param string $database - MySQL Database
*/
protected function __construct($server = NULL, $username = NULL, $password = NULL, $database = NULL) {
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->database = $database;
}
/** Private clone method to prevent cloning of the MySQL_wrapper instance.
* @return void
*/
private function __clone() {
// ... void
}
/** Private unserialize method to prevent unserializing of the MySQL_wrapper instance.
* @return void
*/
private function __wakeup() {
// ... void
}
/** Call function
* @param string $func - function name
* @param string $params - MySQL User
* @param return
*/
public function call($func) {
// Functions without link parameter
$l = array('free_result', 'fetch_assoc', 'num_rows', 'num_fields', 'fetch_object', 'fetch_field_direct');
// Add return value
$r = array('free_result' => TRUE);
// Params
if (func_num_args() >= 2) {
$params = func_get_args();
unset($params[0]);
if ($this->extension == 'mysql') {
$params = in_array($func, $l) ? $params : array_merge($params, array($this->link));
} elseif ($this->extension == 'mysqli') {
$params = in_array($func, $l) ? $params : array_merge(array($this->link), $params);
}
} else {
$params = array($this->link);
}
// Return
if (in_array($func, array_keys($r)) && $this->extension == 'mysqli') {
call_user_func_array("{$this->extension}_{$func}", $params);
return $r[$func];
} else {
return call_user_func_array("{$this->extension}_{$func}", $params);
}
}
/** Connect
* @param string $server - MySQL Host name
* @param string $username - MySQL User
* @param string $password - MySQL Password
* @param string $database - MySQL Database
* @param boolean $newLink - New link
* @return boolean
*/
public function connect($server = NULL, $username = NULL, $password = NULL, $database = NULL, $newLink = FALSE) {
if ($server !== NULL && $username !== NULL && $database !== NULL) {
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->database = $database;
}
if ($this->extension == 'mysql') {
$this->link = @mysql_connect($this->server, $this->username, $this->password, $newLink) or $this->error("Couldn't connect to server: {$this->server}.");
if ($this->link) {
$this->setCharset();
@mysql_select_db($this->database, $this->link) or $this->error("Could not open database: {$this->database}.");
return TRUE;
} else {
return FALSE;
}
} elseif ($this->extension == 'mysqli') {
$this->link = mysqli_connect($this->server, $this->username, $this->password, $this->database);
// Check connection
if (mysqli_connect_errno($this->link)) {
$this->error("Failed to connect to MySQL: " . mysqli_connect_error());
return FALSE;
} else {
$this->setCharset();
return TRUE;
}
}
}
/** Sets the default charset for the current connection.
* @param string $charset - A valid charset name ( If not defined $this->charset whill be used)
* @return boolean
*/
public function setCharset($charset = NULL) {
$this->charset = $charset ? $charset : $this->charset;
$this->call('set_charset', $this->charset) or $this->error("Error loading character set {$this->charset}");
}
/** Checks whether or not the connection to the server is working.
* @param void
* @return boolean
*/
public function ping() {
return $this->call('ping');
}
/** Reconnect to the server.
* @param void
* @return boolean
*/
public function reconnect() {
$this->close();
return $this->connect();
}
/** Close Connection on the server that's associated with the specified link (identifier).
* @param void
*/
public function close() {
$this->call('close') or $this->error("Connection close failed.");
}
/** Execute a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link (identifier).
* @param string $sql - MySQL Query
* @param mixed - array of params to be escaped or one param
* @param mixed - param
* @param mixed - ...
* @return resource or false
*/
public function query($sql) {
if (func_num_args() >= 2) {
$l = func_get_args();
unset($l[0]);
$p = array();
if (is_array($l[1])) {
$l = $l[1];
}
foreach ($l as $k => $v) {
$p['search'][] = "@{$k}";
if (preg_match('/^' . preg_quote($this->statementStart) . '/i', $v)) {
$p['replace'][] = preg_replace('/^' . preg_quote($this->statementStart) . '/i', NULL, $v);
} else {
$p['replace'][] = $this->escape($v);
}
}
$sql = str_replace($p['search'], $p['replace'], $sql);
unset($l, $p);
}
if ($this->logQueries) {
$start = $this->getMicrotime();
}
$this->prevQuery = $sql;
$this->query = $this->call('query', $sql) or $this->error("Query fail: " . $sql);
$this->affected = $this->call('affected_rows');
if ($this->query && $this->logQueries) {
$this->log('QUERY', "EXEC -> " . number_format($this->getMicrotime() - $start, 8) . " -> " . $sql);
}
return $this->query ? $this->query : FALSE;
}
/** Get number of fields in result
* @param resource $query - MySQL Query Result
* @return integer - Retrieves the number of fields from a query
*/
public function numFields($query = 0) {
return intval($this->call('num_fields', $query ? $query : $this->query));
}
/** Get number of rows in result
* @param resource $query - MySQL Query Result
* @return integer - Retrieves the number of rows from a result set
*/
public function numRows($query = 0) {
return intval($this->call('num_rows', $query ? $query : $this->query));
}
/** Get number of rows in result
* @param resource $query - Result resource that is being evaluated ( Query Result )
* @return bool
*/
public function freeResult($query = 0) {
$this->call('free_result', $query ? $query : $this->query) or $this->error("Result could not be freed.");
}
/** Get Columns names into array
* @param string $table - Table name
* @return array $columns - Names of Fields
*/
public function getColumns($table) {
$q = $this->query("SHOW COLUMNS FROM `{$table}`;");
$columns = array();
while ($row = $this->fetchArray($q)) $columns[] = $row['Field'];
$this->freeResult($q);
return $columns;
}
/** Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
* @param resource $query - MySQL Query Result
* @return array or false
*/
public function fetchArray($query = 0) {
$this->query = $query ? $query : $this->query;
if ($this->query) {
return $this->call('fetch_assoc', $this->query);
} else {
$this->error("Invalid Query ID: {$this->query}. Records could not be fetched.");
return FALSE;
}
}
/** Returns array with fetched associative rows.
* @param string $sql - MySQL Query
* @param string $fetchFirst - Fetch only first row
* @return array
*/
public function fetchQueryToArray($sql, $fetchFirst = FALSE) {
if ($fetchFirst) {
$sql = rtrim(trim($sql), ';');
$sql = preg_replace($this->REGEX['LIMIT'], 'LIMIT 1;', $sql);
if (substr($sql, -strlen('LIMIT 1;')) !== 'LIMIT 1;') {
$sql .= ' LIMIT 1;';
}
}
$q = $this->query($sql);
$array = array();
if ($fetchFirst && $this->affected > 0) {
$array = $this->fetchArray($q);
} else {
while ($row = $this->fetchArray($q)) {
$array[] = $row;
}
}
$this->freeResult($q);
return $array;
}
/** Escapes special characters in a string for use in an SQL statement.
* @param string $string - unescaped string
* @return string
*/
public function escape($string) {
if (!version_compare(PHP_VERSION, '5.4.0') >= 0) {
$string = get_magic_quotes_gpc() ? stripslashes($string) : $string;
}
return $this->call('real_escape_string', $string);
}
/** Creates an sql string from an associate array
* @param string $table - Table name
* @param array $data - Data array Eg. $data['column'] = 'val';
* @param string $where - MySQL WHERE Clause
* @param integer $limit - Limit offset
* @return number of updated rows or false
*/
public function arrayToUpdate($table, $data, $where = NULL, $limit = 0) {
if (is_array(reset($data))) {
$cols = array();
foreach (array_keys($data[0]) as $c) {
$cols[] = "`{$c}` = VALUES(`{$c}`)";
}
return $this->arrayToInsert($table, $data, TRUE, implode(', ', $cols));
}
$fields = array();
foreach ($data as $key => $val) {
if (in_array(strtolower($val), $this->reserved)) {
$fields[] = "`{$key}` = " . strtoupper($val);
} elseif (preg_match('/^' . preg_quote($this->statementStart) . '/i', $val)) {
$fields[] = "`{$key}` = " . preg_replace('/^' . preg_quote($this->statementStart) . '/i', NULL, $val);
} else {
$fields[] = "`{$key}` = '{$this->escape($val)}'";
}
}
return (!empty($fields)) ? $this->query("UPDATE `{$table}` SET " . implode(', ', $fields) . ($where ? " WHERE {$where}" : NULL) . ($limit ? " LIMIT {$limit}" : NULL) . ";") ? $this->affected : FALSE : FALSE;
}
/** Creates an sql string from an associate array
* @param string $table - Table name
* @param array $data - Data array Eg. array('column' => 'val') or multirows array(array('column' => 'val'), array('column' => 'val2'))
* @param boolean $ingore - INSERT IGNORE (row won't actually be inserted if it results in a duplicate key)
* @param string $duplicateupdate - ON DUPLICATE KEY UPDATE (The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.)
* @return insert id or false
*/
public function arrayToInsert($table, $data, $ignore = FALSE, $duplicateupdate = NULL) {
$multirow = is_array(reset($data));
if ($multirow) {
$c = implode('`, `', array_keys($data[0]));
$dat = array();
foreach ($data as &$val) {
foreach ($val as &$v) {
if (in_array(strtolower($v), $this->reserved)) {
$v = strtoupper($v);
} elseif (preg_match('/^' . preg_quote($this->statementStart) . '/i', $v)) {
$v = preg_replace('/^' . preg_quote($this->statementStart) . '/i', NULL, $v);
} else {
$v = "'{$this->escape($v)}'";
}
}
$dat[] = "( " . implode(', ', $val) . " )";
}
$v = implode(', ', $dat);
} else {
$c = implode('`, `', array_keys($data));
foreach ($data as &$val) {
if (in_array(strtolower($val), $this->reserved)) {
$val = strtoupper($val);
} elseif (preg_match('/^' . preg_quote($this->statementStart) . '/i', $val)) {
$val = preg_replace('/^' . preg_quote($this->statementStart) . '/i', NULL, $val);
} else {
$val = "'{$this->escape($val)}'";
}
}
$v = "( " . implode(', ', $data) . " )";
}
return (!empty($data)) ? $this->query("INSERT" . ($ignore ? " IGNORE" : NULL) . " INTO `{$table}` ( `{$c}` ) VALUES {$v}" . ($duplicateupdate ? " ON DUPLICATE KEY UPDATE {$duplicateupdate}" : NULL) . ";") ? ($multirow ? TRUE : $this->insertID()) : FALSE : FALSE;
}
/** Imports CSV data to Table with possibility to update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg date format or increment (SQL format only @FIELD is variable with content of that field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or table) - this is important if there is update while inserting (Default: file)
* @param string $newLine - New line delimiter (Default: auto detection use \n, \r\n ...)
* @return number of inserted rows or false
*/
public function importCSV2Table($file, $table, $delimiter = ',', $enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = FALSE) {
$file = file_exists($file) ? realpath($file) : NULL;
$file = realpath($file);
if (!file_exists($file)) {
$this->error('ERROR', "Import CSV to Table - File: {$file} doesn't exist.");
return FALSE;
}
if ($newLine === FALSE) {
$newLine = $this->detectEOL($file);
}
$sql = "LOAD DATA LOCAL INFILE '{$this->escape($file)}' " .
"INTO TABLE `{$table}` " .
"COLUMNS TERMINATED BY '{$delimiter}' " .
"OPTIONALLY ENCLOSED BY '{$enclosure}' " .
"ESCAPED BY '{$this->escape($escape)}' " .
"LINES TERMINATED BY '{$newLine}' " .
($ignore ? "IGNORE {$ignore} LINES" : NULL);
if (!empty($update)) {
if ($getColumnsFrom == 'table') {
$columns = $this->getColumns($table);
} elseif ($getColumnsFrom == 'file') {
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
$columns = explode($delimiter, str_replace($enclosure, NULL, trim($line)));
foreach ($columns as $c) {
preg_match($this->REGEX['COLUMN'], $c) or $this->error("ERROR", "Invalid Column Name: {$c} in CSV file: {$file}. Data can not be loaded into table: {$table}.");
}
}
foreach ($columns as &$c) {
$c = (in_array($c, array_keys($update))) ? '@' . $c : "`{$c}`";
}
$sql .= " (" . implode(', ', $columns) . ") ";
$fields = array();
foreach ($update as $key => $val) $fields[] = "`{$key}` = {$val}";
$sql .= "SET " . implode(', ', $fields);
}
$sql .= ";";
return ($this->query($sql)) ? $this->affected : FALSE;
}
/** Imports (ON DUPLICATE KEY UPDATE) CSV data in Table with possibility to update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg date format or increment (SQL format only @FIELD is variable with content of that field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or table) - this is important if there is update while inserting (Default: file)
* @param string $newLine - New line delimiter (Default: auto detection use \n, \r\n ...)
* @return number of inserted rows or false
*/
public function importUpdateCSV2Table($file, $table, $delimiter = ',', $enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = FALSE) {
$tmp_name = "{$table}_tmp_" . rand();
// Create tmp table
$this->query("CREATE TEMPORARY TABLE `{$tmp_name}` LIKE `{$table}`;");
// Remove auto_increment if exists
$change = array();
$this->query("SHOW COLUMNS FROM `{$tmp_name}` WHERE `Key` NOT LIKE '';");
if ($this->affected > 0) {
while ($row = $this->fetchArray()) {
$change[$row['Field']] = "CHANGE `{$row['Field']}` `{$row['Field']}` {$row['Type']}";
}
$this->freeResult();
}
if ($getColumnsFrom == 'file') {
// Get first line of file
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
$columns = explode($delimiter, str_replace($enclosure, NULL, trim($line)));
foreach ($columns as $c) {
preg_match($this->REGEX['COLUMN'], $c) or $this->error("ERROR", "Invalid Column Name: {$c} in CSV file: {$file}. Data can not be loaded into table: {$table}.");
}
// Drop columns that are not in CSV file
foreach ($this->getColumns($table) as $c) {
if (!in_array($c, $columns, TRUE)) {
$change[$c] = "DROP COLUMN `{$c}`";
}
}
}
if (count($change) > 0) {
$this->query("ALTER TABLE `{$tmp_name}` " . implode(', ', $change) . ";");
}
// Import to tmp
$this->importCSV2Table($file, $tmp_name, $delimiter, $enclosure, $escape, $ignore, $update, $getColumnsFrom, $newLine);
// Copy data
$cols = array();
if ($getColumnsFrom == 'table') {
$columns = $this->getColumns($tmp_name);
}
foreach ($columns as $c) {
$cols[] = "`{$c}` = VALUES(`{$c}`)";
}
$this->query("INSERT INTO `{$table}` ( `" . implode('`, `', $columns) . "` ) SELECT * FROM `{$tmp_name}` ON DUPLICATE KEY UPDATE " . implode(', ', $cols) . ";");
$i = $this->affected;
// Drop tmp table
$this->query("DROP TEMPORARY TABLE `{$tmp_name}`;");
return $i;
}
/** Export table data to CSV file.
* @param string $table - Table name
* @param string $file - CSV File path
* @param mixed $columns - SQL ( * or column names or array with column names)
* @param string $where - MySQL WHERE Clause
* @param integer $limit - Limit offset
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param string $newLine - New line delimiter (Default: \n)
* @param boolean $showColumns - Columns names in first line
* @return - File path
*/
public function exportTable2CSV($table, $file, $columns = '*', $where = NULL, $limit = 0, $delimiter = ',', $enclosure = '"', $escape = '\\', $newLine = '\n', $showColumns = TRUE) {
// Without OUTFILE or as attachment
if ($this->attachment || !$this->mysqlOutFile) {
return $this->query2CSV("SELECT * FROM `$table`" . ($where ? " WHERE {$where}" : NULL) . ($limit ? " LIMIT {$limit}" : NULL), $file, $delimiter, $enclosure, $escape, $newLine, $showColumns);
}
$fh = fopen($file, 'w') or $this->error("ERROR", "Can't create CSV file: {$file}");
if (!$fh) {
return FALSE;
}
fclose($fh);
$file = realpath($file);
unlink($file);
// Put columns into array if not *
if ($columns != '*' && !is_array($columns)) {
$stringColumns = $columns;
$columns = array();
foreach (explode(',', $stringColumns) as $c) {
$columns[] = trim(str_replace(array("'", "`", "\""), NULL, $c));
}
}
// Prepare SQL for column names
if ($showColumns) {
$tableColumnsArr = array();
if ($columns == '*') {
foreach ($this->getColumns($table) as $c)
$tableColumnsArr[] = "'{$c}' AS `{$c}`";
} elseif (is_array($columns)) {
foreach ($columns as $c)
$tableColumnsArr[] = "'{$c}' AS `{$c}`";
}
$columnsSQL = "SELECT " . implode(', ', $tableColumnsArr);
}
$sql = "SELECT " . (is_array($columns) ? '`' . implode('`, `', $columns) . '`' : $columns) . " FROM `{$table}`" . ($where ? " WHERE {$where}" : NULL) . ($limit ? " LIMIT {$limit}" : NULL);
$sql = (($showColumns) ? "SELECT * FROM ( ( " . $columnsSQL . " ) UNION ALL ( {$sql} ) ) `a` " : "{$sql} ") .
"INTO OUTFILE '{$this->escape($file)}' " .
"FIELDS TERMINATED BY '{$delimiter}' " .
"OPTIONALLY ENCLOSED BY '{$enclosure}' " .
"ESCAPED BY '{$this->escape($escape)}' " .
"LINES TERMINATED BY '{$newLine}';";
return ($this->query($sql)) ? $file : FALSE;
}
/** Set attachment var and return object.
* @param void
* @return - obj
*/
function attachment() {
$this->attachment = TRUE;
return $this;
}
/** Export query to CSV file.
* @param string $sql - MySQL Query
* @param string $file - CSV File path
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param string $newLine - New line delimiter (Default: \n)
* @param boolean $showColumns - Columns names in first line
* @return - File path
*/
public function query2CSV($sql, $file, $delimiter = ',', $enclosure = '"', $escape = '\\', $newLine = '\n', $showColumns = TRUE) {
// Without OUTFILE or as attachment
if ($this->attachment || !$this->mysqlOutFile) {
// Do query
$this->query($sql);
if ($this->affected > 0) {
$fh = fopen($this->attachment ? 'php://output' : $file, 'w') or $this->error("ERROR", "Can't create CSV file: {$file}");
if ($fh) {
if ($this->attachment) {
// Send response headers
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . basename($file));
header('Pragma: no-cache');
header('Expires: 0');
$this->attachment = FALSE;
}
$header = FALSE;
while ($row = $this->fetchArray()) {
// CSV header / field names
if ($showColumns && !$header) {
fputcsv($fh, array_keys($row), $delimiter, $enclosure);
$header = TRUE;
}
fputcsv($fh, array_values($row), $delimiter, $enclosure);
}
fclose($fh);
return $this->affected;
} else {
$this->attachment = FALSE;
return FALSE;
}
} else {
$this->attachment = FALSE;
// No records
return 0;
}
}
// Check if location is writable and unlink
$fh = fopen($file, 'w') or $this->error("ERROR", "Can't create CSV file: {$file}");
if (!$fh) {
return FALSE;
}
fclose($fh);
$file = realpath($file);
unlink($file);
// Remove ; from end of query
$sql = trim(rtrim(trim($sql), ';'));
// Prepare SQL for column names
if ($showColumns) {
$r = $this->query((preg_match($this->REGEX['LIMIT'], $sql)) ? preg_replace($this->REGEX['LIMIT'], 'LIMIT 1;', $sql) : $sql . ' LIMIT 1;');
if ($r !== FALSE && $this->affected > 0) {
$columns = $this->fetchArray($r);
$this->freeResult($r);
$tableColumnsArr = array();
foreach ($columns as $k => $v) {
$tableColumnsArr[] = "'{$k}' AS `{$k}`";
}
$columnsSQL = "SELECT " . implode(', ', $tableColumnsArr);
} else {
// No results for this query
return 0;
}
}
// Final query
$sql = (($showColumns && isset($columnsSQL)) ? "SELECT * FROM ( ( " . $columnsSQL . " ) UNION ALL ( {$sql} ) ) `a` " : "{$sql} ") .
"INTO OUTFILE '{$this->escape($file)}' " .
"FIELDS TERMINATED BY '{$delimiter}' " .
"OPTIONALLY ENCLOSED BY '{$enclosure}' " .
"ESCAPED BY '{$this->escape($escape)}' " .
"LINES TERMINATED BY '{$newLine}';";
return ($this->query($sql)) ? $file : FALSE;
}
/** Export query to XML file or return as XML string
* @param string $query - mysql query
* @param string $rootElementName - root element name
* @param string $childElementName - child element name
* @return string - XML
*/
public function query2XML($query, $rootElementName, $childElementName, $file = NULL) {
// Save to file or attachment
if ($this->attachment || !empty($file)) { //echo $file; exit;
$fh = fopen($this->attachment ? 'php://output' : $file, 'w') or $this->error("ERROR", "Can't create XML file: {$file}");
if (!$fh) {
return FALSE;
} elseif ($this->attachment) {
// Send response headers
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename="' . basename($file));
header('Pragma: no-cache');
header('Expires: 0');
$this->attachment = FALSE;
} else {
$file = realpath($file);
}
$saveToFile = TRUE;
} else {
$saveToFile = FALSE;
}
// Do query
$r = $this->query($query);
// XML header
if ($saveToFile) {
fputs($fh, "<?xml version=\"1.0\" encoding=\"" . strtoupper($this->charset) . "\" ?>" . PHP_EOL . "<{$rootElementName}>" . PHP_EOL);
} else {
$xml = "<?xml version=\"1.0\" encoding=\"" . strtoupper($this->charset) . "\" ?>" . PHP_EOL;
$xml .= "<{$rootElementName}>" . PHP_EOL;
}
// Query rows
while ($row = $this->call('fetch_object', $r)) {
// Create the first child element
$record = "\t<{$childElementName}>" . PHP_EOL;
for ($i = 0; $i < $this->call('num_fields', $r); $i++) {
// Different methods of getting field name for mysql and mysqli
if ($this->extension == 'mysql') {
$fieldName = $this->call('field_name', $r, $i);
} elseif ($this->extension == 'mysqli') {
$colObj = $this->call('fetch_field_direct', $r, $i);
$fieldName = $colObj->name;
}
// The child will take the name of the result column name
$record .= "\t\t<{$fieldName}>";
// Set empty columns with NULL and escape XML entities
if (!empty($row->$fieldName)) {
$record .= htmlspecialchars($row->$fieldName, ENT_XML1);
} else {
$record .= NULL;
}
$record .= "</{$fieldName}>" . PHP_EOL;
}
$record .= "\t</{$childElementName}>" . PHP_EOL;
if ($saveToFile) {
fputs($fh, $record);
} else {
$xml .= $record;
}
}
// Output
if ($saveToFile) {
fputs($fh, "</{$rootElementName}>" . PHP_EOL);
fclose($fh);
return TRUE;
} else {
$xml .= "</{$rootElementName}>" . PHP_EOL;
return $xml;
}
}
/** Create table from CSV file and imports CSV data to Table with possibility to update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg date format or increment (SQL format only @FIELD is variable with content of that field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or generate) - this is important if there is update while inserting (Default: file)
* @param string $newLine - New line delimiter (Default: auto detection use \n, \r\n ...)
* @return number of inserted rows or false
*/
public function createTableFromCSV($file, $table, $delimiter = ',', $enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = FALSE) {
$file = file_exists($file) ? realpath($file) : NULL;
if ($file === NULL) {
$this->error('ERROR', "Create Table form CSV - File: {$file} doesn't exist.");
return FALSE;
} else {
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
$data = explode($delimiter, str_replace($enclosure, NULL, trim($line)));
$columns = array();
$i = 0;
foreach ($data as $c) {
if ($getColumnsFrom == 'generate') {
$c = 'column_' . $i++;
}
if (preg_match($this->REGEX['COLUMN'], $c)) {
$columns[] = "`{$c}` BLOB NULL";
} else {
$this->error('ERROR', "Invalid column name: {$c} in file: {$file}");
return FALSE;
}
}
$this->query("CREATE TABLE `{$table}` ( " . implode(', ', $columns) . " ) ENGINE=InnoDB DEFAULT CHARSET={$this->charset};");
if ($this->importCSV2Table($file, $table, $delimiter, $enclosure, $escape, $ignore, $update, ($getColumnsFrom == 'generate') ? 'table' : 'file', $newLine) > 0) {
$columns = $this->fetchQueryToArray("SELECT * FROM `{$table}` PROCEDURE ANALYSE ( 10, 30 );", FALSE);
$change = array();
foreach ($columns as $c) {
$c['Field_name'] = implode('`.`', explode('.', $c['Field_name']));
$change[] = "CHANGE `{$c['Field_name']}` `{$c['Field_name']}` {$c['Optimal_fieldtype']}";
}
$this->query("ALTER TABLE `{$table}` " . implode(', ', $change) . ";");
}
}
}
/** Rename table(s)
* @param array $table - Names of the tables eg -> array('old_table' => 'new_table') or array('table1' => 'tmp_table', 'table2' => 'table1', 'tmp_table' => 'table1')
* @return resource or false
*/
public function renameTable($table) {
$rename = array();
foreach ($table as $old => $new) {
$rename[] = "`{$old}` TO `{$new}`";
}
return $this->query("RENAME TABLE " . implode(', ', $rename) . ";");
}
/** Copy table structure or structure and data.
* @param string $table - Table name
* @param string $new_table - New table name
* @param boolean $data - Copy table data
* @return resource or false
*/
public function copyTable($table, $new_table, $data = TRUE) {
$r = $this->query("CREATE TABLE `{$new_table}` LIKE `{$table}`;");
return ($r && $data) ? $this->query("INSERT INTO `{$new_table}` SELECT * FROM `{$table}`;") : $r;
}
/** Truncate table
* @param string $table - Table name
* @return resource or false
*/
public function truncateTable($table) {
return $this->query("TRUNCATE TABLE `{$table}`;");
}
/** Drop table(s)
* @param array $table - Names of the tables eg -> array('table1', 'table2')
* @param boolean $if_exists - Use IF EXISTS to prevent an error from occurring for tables that do not exist.
* @return resource or false
*/
public function dropTable($table, $if_exists = TRUE) {
return $this->query("DROP TABLE " . ($if_exists ? "IF EXISTS " : NULL) . "`" . (is_array($table) ? implode('`, `', $table) : $table) . "`;");
}
/** Data Base size in B / KB / MB / GB / TB
* @param string $sizeIn - Size in B / KB / MB / GB / TB
* @param integer $round - Round on decimals
* @return - Size in B / KB / MB / GB / TB
*/
public function getDataBaseSize($sizeIn = 'MB', $round = 2) {
$r = $this->query("SELECT ROUND( SUM( `data_length` + `index_length` ) " . str_repeat('/ 1024 ', array_search(strtoupper($sizeIn), array('B', 'KB', 'MB', 'GB', 'TB'))) . ", {$round} ) `size` FROM `information_schema`.`TABLES` WHERE `table_schema` LIKE '{$this->database}' GROUP BY `table_schema`;");
if ($r !== FALSE) {
$row = $this->fetchArray($r);
$this->freeResult($r);
return $row['size'];
} else {
return FALSE;
}
}
/** Retrieves the ID generated for an AUTO_INCREMENT column by the previous query.
* @param void
* @return integer
*/
public function insertID() {
return $this->call('insert_id');
}
/** Retrieves the number of rows from table based on certain conditions.
* @param string $table - Table name
* @param string $where - WHERE Clause
* @return integer or false
*/
public function countRows($table, $where = NULL) {
$r = $this->query("SELECT COUNT( * ) AS count FROM `{$table}` " . ($where ? " WHERE {$where}" : NULL) . ";");
if ($r !== FALSE) {
$row = $this->fetchArray($r);
$this->freeResult($r);