-
Notifications
You must be signed in to change notification settings - Fork 0
/
class.PDO-MySQL.php
1848 lines (1800 loc) · 52.6 KB
/
class.PDO-MySQL.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
/**
* MySQL Class File
* @package craig
*
* @version 29th January 2012
* @copyright Craig Rayner 2009-2011<br />
* Vocational Education Record Sysem for Registered Training Organisation: Australia.<br />
* Copyright (C) 2004-2011 Craig A. Rayner<br />
* <br />
* This program is free software: you can redistribute it and/or modify<br />
* it under the terms of the GNU General Public License as published by<br />
* the Free Software Foundation, either version 3 of the License, or<br />
* any later version.<br />
* <br />
* This program is distributed in the hope that it will be useful,<br />
* but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br />
* GNU General Public License for more details.<br />
* <br />
* You should have received a copy of the GNU General Public License<br />
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* MySQL Database Record Manipulator in PHP using PDO
*
* @author Craig Rayner
* @copyright Craig Rayner 2009-2009
* @since 26th June 2009
* @package craig
*
* @version 29th January 2012
*
Information Record Sysem for Registered Training Organisation: Australia.
Copyright (C) 2004-2011 Craig A. Rayner
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 3 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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class mysql_PDO {
/**
* Version: Current Class Version Number
* @access public
* @var string
*/
var $version = '29th January 2012';
/**
* Data Base Name
* @access public
* @var string
*/
var $DataBaseName;
/**
* Data Base Index
* @access public
* @var integer
*/
var $DataBaseIndex;
/**
* Site is under Development
* @access public
* @var boolean
*/
var $TestMode = false;
/**
* Which Method was last called
* @access public
* @var string
*/
var $FunctionCalled;
/**
* Last MySQL Error
* @access public
* @var string
*/
var $error;
/**
* Last MySQL Error Number
* @access public
* @var integer
*/
var $errno;
/**
* Last MySQL Error Number
* @access public
* @var integer
*/
var $PDOErrno;
/**
* Last MySQL Access Status
* @access public
* @var boolean
*/
var $ok;
/**
* Pointer to the Current (or Next) Row
* @access public
* @var integer
*/
var $thisrow;
/**
* Total number of rows in the result set.
* @access public
* @var integer
*/
var $lastrow;
/**
* Next available AUTOINCREMENT
* @access public
* @var integer
*/
var $next_id;
/**
* Number of Rows Altered by last MySQL Access
* @access public
* @var integer
*/
var $AffectedRows;
/**
* Has Purge Changes been done
* @access private
* @var boolean
*/
var $PurgeChangesDone;
/**
* List of Log Exceptions
* @access public
* @var array
*/
var $DoNotLog;
/**
* Last Query
* @access public
* @var string
*/
var $LastQuery;
/**
* MySQLi
* @access public
* @var object
*/
var $PDO;
/**
* Result Object for Queries Executed
* @access public
* @var object
*/
var $result;
/**
* Query to be Executed or Accessed.
* @access public
* @var string
*/
var $query;
/**
* Table Name
* @access public
* @var string
*/
var $table;
/**
* The Identifier Name (Unique) in a Table
* @access public
* @var string
*/
var $identifier;
/**
* Field Data from table
* @access public
* @var array
*/
var $field;
/**
* Data retireved from Select
* @access public
* @var array
*/
var $fetch;
/**
* Field Information
* @access public
* @var array
*/
var $FieldData;
/**
* Character Set
* @access public
* @var string
*/
var $CharacterSet = 'utf8';
/**
* Collate
* @access public
* @var string
*/
var $Collate = 'utf8_bin';
/**
* PDO Database Access Constructor
*
* @version 26th June 2009
* @since 26th June 2009
* @param string The database name to set for this session.
* @return void
*/
function mysql_PDO($database = '') {
global $version;
$this->FunctionCalled = 'PDO Record Constructor';
$this->DataBaseName = $database;
$this->ClearField();
if (TEST_MODE) {
$this->TestMode = true;
}
if (defined("COLLATE")) {
$this->Collate = COLLATE;
}
if (defined("CHARACTERSET")) {
$this->CharacterSet = CHARACTERSET;
}
$this->LogCall('mysql_record($database = '.strval($database).')');
if (isset($version['class.PDO-MySQL.php']))
return;
$version['class.PDO-MySQL.php'] = $this->version;
$this->DoNotLog = array();
$this->LastQuery = '';
$this->DoNotLog[] = $this->query = "CREATE TABLE IF NOT EXISTS `".PRE_NAME."changes` (
`id` bigint(11) unsigned zerofill NOT NULL auto_increment,
`tablename` varchar(40) NOT NULL default '',
`tablekey` varchar(30) NOT NULL default '',
`changedate` datetime default NULL,
`olddata` longtext NOT NULL,
`querytype` enum('Update','Insert','Delete') NOT NULL default 'Update',
`user` varchar(50) NOT NULL default 'Unknown',
PRIMARY KEY (id)
) ";
$this->ExecuteQuery($this->query);
$this->DoNotLog[] = $this->query = "CREATE TABLE IF NOT EXISTS `".PRE_NAME."PurgeData` (
`id` INT( 11 ) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`TableName` VARCHAR( 250 ) NOT NULL ,
`TableIdentifier` VARCHAR( 250 ) NOT NULL DEFAULT 'id' ,
`method` ENUM( 'Records', 'Date', 'TableSize' ) NOT NULL DEFAULT 'Records',
`size` INT( 11 ) NOT NULL DEFAULT '1000',
`multiplier` ENUM( 'Nil', 'kB', 'MB' ) NOT NULL DEFAULT 'Nil',
`RowDate` VARCHAR( 250 ) NULL ,
UNIQUE (
`TableName`
)
) COMMENT = 'Holds data of Tables to Purge'";
$this->ExecuteQuery($this->query);
if (! CRON_ON)
$this->PurgeChanges();
}
/**
* Log of the Methods Called.
*
* @version 26th June 2009
* @since 26th June 2009
* @param string Method Name
* @return void
*/
function LogCall($method) {
if (! $this->TestMode)
return;
global $version;
$x = explode(' ', microtime());
$version['class.PDO-MySQL.php '.strval(number_format($x[1] + mb_substr($x[0], 1), 6, '.', ''))] = $method;
return ;
}
/**
* Clear Fields and Query
*
* @access public
* @version 26th June 2009
* @since 26th June 2009
* @return void
*/
function ClearField() {
$this->LogCall('ClearField()');
unset($this->field, $this->query);
return ;
}
/**
* Execute Query
*
* All hell breaks loose as this will execute ANY query<br />
* It does not record its changes at all. <b>Still in development.</b><br />
* sets ok, error, errno
* @version 5th July 2009
* @since 26th June 2009
* @param string $query New query into object, defaults to object->query
* @return integer Number of affected rows.
*/
function ExecuteQuery($query = 'NO QUERY') {
$this->LogCall('ExecuteQuery($query = '.strval($query).')');
$this->FunctionCalled = 'Execute Query: ';
$this->OpenDatabase();
if ($query != "NO QUERY")
$this->query = $query;
$this->LastQuery = $this->query;
$this->ClearError();
$result = $this->PDO->exec($this->query);
$this->AffectedRows = $result;
if (intval($this->PDO->errorCode()) !== 0) {
$this->SetError("Execute Query: ", $this->PDO->errorCode());
if ($this->TestMode)
$this->debug();
} else {
$this->SaveChanges('', 'Execute');
}
$result = NULL;
$this->PDO = NULL;
unset($result, $this->PDO);
return $this->AffectedRows;
}
/**
* Open Database
*
* Change the following GLOBAL variables to your MySQL requirements with the config data<br />
* (config data kept in a different file for security reasons.)<br />
* MYSQL_HOST<br />
* MYSQL_USER<br />
* MYSQL_PASS<br />
* MYSQL_DB
*
* @access public
* @version 31st August 2011
* @since 26th June 2009
* @return void
*/
function OpenDatabase() {
$this->LogCall('OpenDatabase()');
$this->dBName = explode(',', MYSQL_DB);
$HostName = explode(',', MYSQL_HOST);
$UserName = explode(',', MYSQL_USER);
$PassWord = explode(',', MYSQL_PASS);
$this->DataBaseIndex = 0;
if ($this->DataBaseName !== '') {
$this->DataBaseIndex = current(array_keys($this->dBName, $this->DataBaseName));
}
$this->DataBaseName = $this->dBName[$this->DataBaseIndex];
try {
$this->PDO = new PDO(
'mysql:host='.$HostName[$this->DataBaseIndex].';dbname='.$this->DataBaseName,
$UserName[$this->DataBaseIndex],
$PassWord[$this->DataBaseIndex],
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ".$this->CharacterSet, PDO::ATTR_PERSISTENT => true)
);
} catch (PDOException $e){
$this->SetError("Error!: " . $e->getMessage());
$this->debug();
}
return ;
}
/**
* Clear the Error Details
*
* @version 29th June 2009
* @since 26th June 2009
* @return void
*/
function ClearError() {
$this->LogCall('ClearError()');
$this->PDOErrno = 0;
$this->error = '';
$this->errno = 0;
$this->ok = true;
return ;
}
/**
* Save Changes
*
* Saves the changes of an insert or update query into the changes table.
* @version 26th June 2009
* @since 26th June 2009
* @private
* @param string The data that has changed.
* @param string The type of data change.
* @return void
*/
private function SaveChanges($data, $type){
$this->LogCall('SaveChanges($data = '.strval($data).', $type = '.strval($type).')');
if ($handle = @gzopen(MYSQL_LOGPATH.'sql'.date('Y-m-d').'.log.gz', 'a9')) {
if (is_array($this->DoNotLog))
if (! in_array($this->LastQuery, $this->DoNotLog))
gzwrite($handle, date('His').':'.$this->LastQuery.";\n");
gzclose($handle);
}
if (empty($data))
return ;
$skip = explode(',', SKIP_CHANGES);
if (in_array($this->table, $skip))
return ;
$data = addslashes($_SERVER['SCRIPT_FILENAME'].'||'.$data);
if (empty($_SESSION['user']))
$_SESSION['user'] = 'System';
$change = "INSERT INTO `".PRE_NAME."changes`
SET `querytype` ='".$type."',
`user` ='".$_SESSION['user']."',
`changedate` ='".date('Y-m-d H:i:s')."',
`olddata` ='".$data."',
`tablename` ='".$this->table."',
`tablekey` ='".$this->field[$this->identifier]."'";
$result = $this->PDO->query($change);
$result = NULL;
unset($result);
return ;
}
/**
* Initiate Query
*
* Same as select_query except this defaults the pointer to the first record of the record set.<br />
* Sets the same variables as select_query, as this function calls select query after setting the query and thisrow = 0.
* @version 26th June 2009
* @since 26th June 2009
* @param string The new query, defaults to object->query
* @param integer The pointer value should you wish to retrieve, defaults to first record.
* @return array Table Fields
*/
function InitiateQuery($text, $thisrow = -1) {
$this->LogCall('InitiateQuery($text = '.strval($text).', $thisrow = '.strval($thisrow).')');
$this->FunctionCalled = 'Initiate Query: ';
$this->ClearField();
$this->thisrow = 0;
if ($thisrow != -1)
$this->thisrow = $thisrow;
$this->SelectQuery($text, $thisrow);
return $this->field;
}
/**
* Select Query
*
* Initiates a query and returns the row indicated by thisrow<br />
* <br />
* sets the field array with the results (slashes striped from field) or<br />
* sets error / errno with the problem.<br />
* sets ok to indicate success<br />
* sets query, thisrow, lastrow, result
* @version 26th June 2009
* @since 26th June 2009
* @param string A new query to replace the internal query.
* @param integer the pointer to the row to retrieve.
* @return array The table fields
*/
function SelectQuery($query = "NO QUERY", $thisrow = -1) {
$this->LogCall('SelectQuery($query = '.strval($query).', $thisrow = '.strval($thisrow).')');
$this->FunctionCalled = 'Select Query: ';
if ($query === 'Build') {
$this->query = $this->BuildSelectQuery();
} elseif ($query !== "NO QUERY") {
$this->query = $query;
}
if ($thisrow != -1) {
$this->thisrow = $thisrow;
}
$this->ClearError();
$this->OpenDatabase();
$this->result = $this->PDO->query($this->query);
$err = $this->PDO->errorCode();
if (intval($err) > 0) {
$this->SetError("Select 01: ".print_r($this->PDO->errorInfo(), true), $err);
if ($this->TestMode) {
switch ($this->errno) {
case 1146:
break;
default:
$this->debug();
}
}
}
if (is_object($this->result)) {
$this->fetch = $this->result->fetchAll(PDO::FETCH_ASSOC);
$this->lastrow = 0;
if ($this->ok) {
$this->lastrow = count($this->fetch);
if ($this->thisrow > $this->lastrow - 1)
$this->thisrow = $this->lastrow - 1;
if ($this->thisrow < 0)
$this->thisrow = 0;
if (empty($this->fetch[$this->thisrow]) AND $this->lastrow > 0) {
$this->SetError("Select 02: Failed to set the pointer in the query. Pointer: .".$this->thisrow.' in '.$this->lastrow);
if ($this->TestMode)
$this->debug();
} else {
if ($this->lastrow > 0) {
foreach ($this->fetch[$this->thisrow] as $q=>$w) {
$this->field[$q] = stripslashes($w);
}
}
}
}
} else {
$this->thisrow = 0;
$this->lastrow = 0;
$this->SetError('The query returned an empty set.', 9997);
$this->field = array();
$this->fetch = array();
}
if (! isset($this->field))
$this->field = array();
$this->result = NULL;
$this->PDO = NULL;
unset($this->result, $this->PDO);
return $this->field;
}
/**
* Build the Select Query
*
* @version 26th June 2009
* @since 26th June 2009
* @return string The Query built from the details given.
*/
function BuildSelectQuery() {
$this->LogCall('BuildSelectQuery()');
if (empty($this->table)) {
$this->SetError("BuildSelectQuery: Requires that the table property be set: $this->table");
$this->debug();
}
if (empty($this->select)) {
$this->select = '*';
}
$query = 'SELECT ';
$ss = explode(",", $this->select);
foreach($ss as $q=>$w) {
$query .= $this->TestforTableNames(trim($w)).",\n";
}
$query = mb_substr($query, 0, -2) ;
$query .= "\n FROM ";
$ss = explode(",", $this->table);
foreach($ss as $q=>$w) {
$query .= $this->AddTablePrefix($w).",\n";
}
$query = mb_substr($query, 0, -2) ;
// JOIN
if (! empty($this->Join)) {
$query .= "\n ".$this->BuildJoinString();
}
// WHERE
if (! empty($this->where)) {
$query .= "\n WHERE ".$this->BuildWhereString();
}
// ORDERBY
if (! empty($this->OrderBy)) {
$query .= "\n ORDER BY ".$this->BuildOrderByString();
}
return $query;
}
/**
* Test for Table Names
*
* Test for Table Names on the front of Field Names and add prefix if necessary.
* @version 26th June 2009
* @since 26th June 2009
* @param string The field name under test.
* @return string The modified field name.
*/
function TestforTableNames($field) {
$this->LogCall('TestforTableNames($field = '.strval($field).')');
if ($field === '*')
return $field;
if ($field === '(')
return $field;
if ($field === ')')
return $field;
$ss = explode(".", $field);
if (count($ss) === 2) {
$field = $this->AddTablePrefix($ss[0]).".`".$ss[1]."`";
} else {
$field = '`'.$field.'`';
}
if (mb_substr($field, mb_strlen($field)-3, 3) === "`*`")
$field = mb_substr($field, 0, mb_strlen($field) - 3)."*";
return $field;
}
/**
* Add Table Prefix
*
* Test for and if necessary add the table prefix to the tablename.<br />
* The Prefix is defined in the config file as PRE_NAME
*
* @version 26th June 2009
* @since 26th June 2009
* @param string The table name to test and add the prefix too.
* @return string The corrected table name.
*/
function AddTablePrefix($table) {
$this->LogCall('AddTablePrefix($table = '.strval($table).')');
$x = PRE_NAME;
if (empty($x))
return "`".$table."`";
if (mb_strpos($table, $x) === 0)
return "`".$table."`";
return "`".$x.$table."`";
}
/**
* Build Where String
*
* Rules for the Where string array.<br />
* Each array key must end with one of the following characters:<br />
* F = Field Name<br />
* V = Value to test for in the field<br />
* C = Comparitor between the field and value. (=, !=, >, <=, LIKE, etc)<br />
* L = Linking Structure such as (, ), AND, OR, etc
* @version 26th June 2009
* @since 26th June 2009
* @return string The WHERE clause of an SQL query.
*/
function BuildWhereString() {
$this->LogCall('BuildWhereString()');
ksort($this->where);
unset($y, $wh, $f, $c, $l, $v);
foreach($this->where as $q=>$w) {
$k = mb_substr($q, 0, -1);
if (@$y !== $k) {
if (! empty($f))
@$wh .= $this->TestforTableNames($f).' '.$c.' '.$v;
if (! empty($l))
$wh .= "\n ".$l.' ';
$y = $k;
unset($c, $f, $l, $v);
}
$t = mb_substr($q, mb_strlen($q) - 1, 1);
switch ($t) {
case "F":
$f = $w;
break;
case "V":
$v = $w;
break;
case "C":
$c = $w;
break;
case "L":
$l = $w;
break;
default:
$this->SetError('Unable to parse the where clause in the SQL query correctly.');
$this->debug();
}
}
if (! empty($f)) {
@$wh .= " ".$this->TestforTableNames(@$f).' '.@$c.' '.@$v." ".@$l."\n ";
} elseif (! empty($l)) {
$wh .= " ".$l."\n ";
} else {
$wh .= "\n ";
}
return $wh;
}
/**
* Build OrderBy String
*
* @version 26th June 2009
* @since 26th June 2009
* @return string The ORDERBY clause of an SQL query.
*/
function BuildOrderByString() {
$this->LogCall('BuildOrderByString()');
$ss = explode(",", $this->OrderBy);
unset($ob);
foreach($ss as $q=>$w) {
$w = trim($w);
if (mb_strpos($w, 'ASC') === mb_strlen($w) - 3) {
$f = $this->TestforTableNames(trim(mb_substr($w, 0, -3)));
$d = 'ASC';
} elseif (mb_strpos($w, 'DESC') === mb_strlen($w) - 4) {
$f = $this->TestforTableNames(trim(mb_substr($w, 0, -4)));
$d = 'DESC';
} else {
unset($d);
$f = $this->TestforTableNames($w);
}
@$ob .= $f.' '.@$d.",\n ";
}
$ob = mb_substr($ob, 0, -3)."\n ";
return $ob;
}
/**
* Set the Error Details
*
* @version 14th July 2009
* @since 26th June 2009
* @param mixed Error Description
* @param string Error Number
* @return void
*/
function SetError($error, $errno = '9998') {
$this->LogCall('SetError-1($error = '.strval($error).', $errno = '.strval(intval($errno)).')');
$this->ClearError();
if (is_object($this->PDO)) {
if (is_array($this->PDO->errorInfo())) {
$x = $this->PDO->errorInfo();
$this->errno = intval($x[1]);
$this->error = $error .'<br />'.strval($x[2]);
$this->PDOErrno = intval($x[0]);
} else {
$this->error = $error;
$this->errno = intval($errno);
$this->PDOErrno = 0;
}
} else {
$this->error = $error;
$this->errno = intval($errno);
$this->PDOErrno = 0;
}
if ( intval($this->errno) === 0 ){
$this->error = $error;
$this->errno = intval($errno);
$this->PDOErrno = 0;
}
$this->ok = false;
return ;
}
/**
* Debug
*
* Prints the entire object to the browser.
* @version 26th June 2009
* @since 26th June 2009
* @param boolean Set to false so that program execution does not stop.
* @return void
*/
function debug($stop = true) {
$this->LogCall('debug($stop = '.strval(intval($stop)).')');
global $version;
$x = "MySQL<pre>\n";
$x .= var_export($this, true);
$x .= "</pre>\n";
$x .= "Version<pre>\n";
$x .= var_export($version, true);
$x .= "</pre>\n";
echo $x;
$x .= "Server<pre>\n";
$x .= var_export($_SERVER, true);
$x .= "</pre>\n";
if (! $this->TestMode) {
mb_send_mail('webmaster@'.SERVER_NAME, 'MySQL Error: '.SERVER_NAME, $x);
}
if ($stop) {
exit();
}
}
/**
* Retrieve Row from an established query.
*
* sets the field array with the results (slashes striped from field) or<br />
* sets error / errno with the problem.<br />
* sets ok to indicate success<br />
* sets thisrow<br />
* Use this function after setting the query to retrieve successive row, without the overhead of
* a new select query to the database, therefore speedier replies.
* @param boolean Increment thisrow after retrieving the row.
* @param integer Increment thisrow after reading table row.
* @version 26th June 2009
* @since 26th June 2009
* @return array The fields called in the query.
*/
function RetrieveRow($inc = false, $thisrow = -1) {
$this->LogCall('RetrieveRow($inc = '.strval($inc).', $thisrow = '.strval($thisrow).')');
$this->functionCalled = 'Retrieve Row';
if ($thisrow != -1)
$this->thisrow = $thisrow;
if (! is_array($this->fetch)) {
$this->SetError('Fetch array is not available in RetrieveRow.');
$this->debug();
}
$this->field = array();
if (is_array($this->fetch[$this->thisrow]))
foreach ($this->fetch[$this->thisrow] as $q=>$w) {
$this->field[$q] = stripslashes($w);
}
if ($inc)
$this->thisrow++;
if (! is_array($this->field))
$this->field = array();
return $this->field;
}
/**
* Extract ENUM array
*
* @version 26th June 2009
* @since 26th June 2009
* @param string table
* @param string field
* @param boolean Alpha-Numeric Sort
* @return array
*/
function ExtractENUMArray($table, $field, $sort = false) {
$this->LogCall('ExtractENUMArray($table = '.strval($table).', $field = '.strval($field).', $sort = '.strval($sort).')');
$rr = $this->InitiateQuery("SHOW COLUMNS FROM `".$table."` WHERE `field` = '".$field."'");
if ($this->lastrow !== 1)
return array();
$r = mb_substr($rr['Type'], 6);
$x = explode("','", mb_substr($r, 0, -2));
if ($sort)
sort($x);
return $x;
}
/**
* Save Record
*
* Inserts or Updates a record depending on how variables have been set.<br />
* only updates if field[identifier] != 0<br />
* if field[identifier] != 0 and table.identifier == 0 then AN insert is done.
* Will set a field as `RecordChange` = date(Y-m-d H:i:s)
* @version 29th January 2012
* @since 26th June 2009
* @param string New table name, if not set used object table name
* @param string New Identifier with the table name, or uses object idenetifier name.
* @param array Adds fields to array to be set to NULL if field value is EMPTY.
* @access public
* @return integer The pointer to the record saved.
*/
function SaveRecord($table = "NO TABLE", $identifier = 'Not Set') {
$this->LogCall('SaveRecord($table = '.strval($table).', $identifier = '.strval($identifier).')');
$this->functionCalled = 'Save Record: ';
$result = NULL;
if ($table != "NO TABLE")
$this->table = $table;
if ($identifier != 'Not Set')
$this->identifier = $identifier;
if (empty($this->identifier)) {
$this->SetError("The Table Identifier has not been set in MySQL_record.");
$this->debug();
}
if (empty($this->table)) {
$this->SetError("The Table Name has not been set in MySQL_record.");
$this->debug();
}
//Add a Record Change Field. Will be deleted if not available.
$this->field['RecordChange'] = date('Y-m-d H:i:s');
//Remove any invalid field from the list of fields.
$field = $this->field;
$col = array();
if (isset($this->query))
$query = $this->query;
$thisrow = $this->thisrow;
$lastrow = $this->lastrow;
if (isset($this->result))
$result = $this->result;
$fetch = $this->fetch;
$this->InitiateQuery('SHOW COLUMNS FROM `'.$this->table.'`');
$this->FieldDetails = array();
while ($this->thisrow < $this->lastrow) {
$rr = $this->RetrieveRow(true);
$this->FieldDetails[$rr['Field']] = $rr;
$col[$this->field['Field']] = 'Valid';
}
if (is_array($field)) {
foreach ($field as $q=>$w) {
if (isset($col[$q]))
if ($col[$q] != 'Valid')
unset($field[$q]);
}
}
if (is_array($field)) {
foreach ($field as $q=>$w) {
if (! get_magic_quotes_gpc()) {
$field[$q] = addslashes($w);
} else {
$field[$q] = $w;
}
}
}
$this->field = $field;
if (empty($this->field[$this->identifier]) OR intval($this->field[$this->identifier]) == 0) {
$this->InsertRecord();
} else {
$x = $this->InitiateQuery("SELECT `".$this->identifier."`
FROM `".$this->table."`
WHERE `".$this->identifier."` = ".$this->field[$this->identifier]);
$this->field = $field;
if (empty($x[$this->identifier])) {
$this->InsertRecord();
} else {
$this->UpdateRecord();
}
}
$this->query = $query;
$this->lastrow = $lastrow;
$this->thisrow = $thisrow;
$this->PDO = NULL;
$this->result = NULL;
unset($this->result, $this->PDO);
$this->result = $result;
$this->fetch = $fetch;
return $this->field[$this->identifier];
}
/**
* Update Record
*
* Change a stored record in a MySQL table.
* @version 15th July 2011<br />
* 3rd July 2009: Automated detection of field that can be set to NULL.
* @since 26th June 2009
* @private
* @return void
*/
private function UpdateRecord() {
$this->LogCall('UpdateRecord($Null = array())');
$this->functionCalled = 'Update Record: ';
if (empty($this->identifier)) {
$this->SetError("The Table Identifier has not been set in MySQL class.");
$this->debug();
}
if (empty($this->table)) {
$this->SetError("The Table Name has not been set in MySQL class.");
$this->debug();
}
$this->OpenDatabase();
$exists = false;
$x = 0;
$this->ok = true;
if ($this->field[$this->identifier] == 0) {
$this->SetError("You can only modify an existing record. Please
select the record you wish to modify before attempting to modify data.");
if ($this->TestMode)
$this->debug();
}
if ($this->ok) {
$query = "SELECT *
FROM `".$this->table."`
WHERE `".$this->identifier."` = ".$this->field[$this->identifier];
$result = $this->PDO->query($query);
$row = $result->fetchall(PDO::FETCH_ASSOC);
$result = NULL;
$this->PDO = NULL;
unset($result, $this->PDO);
$field = $this->field;
$this->InitiateQuery('SHOW COLUMNS FROM `'.$this->table.'`');
$this->FieldDetails = array();
while ($this->thisrow < $this->lastrow) {
$rr = $this->RetrieveRow(true);
$this->FieldDetails[$rr['Field']] = $rr;
$col[$this->field['Field']] = 'Valid';
}
$row = $row[0];
$this->OpenDatabase();
unset($exist);
unset($update);
$this->field = $field;
unset($field);
$field = array();
foreach($row as $key => $value) {
if (($this->EscapePost($value) !== $this->EscapePost($this->field[@$key]))) {
@$exist .= "`".$key.'` = '.$this->EscapePost($value).'|,| ';
$field[] = $key;
}
}
if (count($field) === 1 AND in_array('RecordChange', $field)) {
$field = array();
unset($exist);
}
if (! isset($exist)) {
$this->SetError("You made no changes to your record. No action taken.", '9999');
return;
}
if ($this->ok) {
$update = '';
foreach($this->field as $key => $value) {
if (isset($this->FieldDetails[$key])) {
$e = explode('(', $this->FieldDetails[$key]['Type']);
switch ($e[0]){
case 'int':
$update .= "`".$key."` = ".intval($this->EscapePost($value)).", ";
break;
case 'tinyint':
$update .= "`".$key."` = ".intval($this->EscapePost($value)).", ";
break;