-
Notifications
You must be signed in to change notification settings - Fork 4
/
mysql.class.php
3704 lines (3528 loc) · 98 KB
/
mysql.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
/**
* Ultimate MySQL Wrapper Class for PHP 5.x
*
*
* Contributions from
* Frank P. Walentynowicz
* Larry Wakeman
* Nicola Abbiuso
* Douglas Gintz
* Emre Erkan
* Vincent van Daal
* Xander Groesbeek (SQLValue:int quoting; QueryArray tweak)
* Ger Hobbelt
*
* <ul>
* <li> Establish MySQL server connections easily
* <li> Execute SQL queries
* <li> Retrieve query results into objects or arrays
* <li> Retrieve the last inserted ID
* <li> Manage transactions (transaction processing)
* <li> Retrieve the list tables of a database
* <li> Retrieve the list fields of a table (or field comments)
* <li> Retrieve the length or data type of a field
* <li> Measure the time a query takes to execute
* <li> Display query results in an HTML table
* <li> Easy formatting for SQL parameters and values
* <li> Generate SQL Selects, Inserts, Updates, and Deletes
* <li> Error handling with error numbers and text
* <li> And much more!
* </ul>
*
* Feb 02, 2007 - Written by Jeff Williams (Initial Release)
* Feb 11, 2007 - Contributions from Frank P. Walentynowicz
* Feb 21, 2007 - Contribution from Larry Wakeman
* Feb 21, 2007 - Bug Fixes and PHPDoc
* Mar 09, 2007 - Contribution from Nicola Abbiuso
* Mar 22, 2007 - Added array types to RecordsArray and RowArray
* Jul 01, 2007 - Class name change, constructor values, static methods, fixed
* Jul 16, 2007 - Bug fix, removed test, major improvements in error handling
* Aug 11, 2007 - Added InsertRow() and UpdateRow() methods
* Aug 19, 2007 - Added BuildSQL static functions, DeleteRows(), SelectRows(),
* IsConnected(), and ability to throw Exceptions on errors
* Sep 07, 2007 - Enhancements to SQL SELECT (column aliases, sorting, limits)
* Sep 09, 2007 - Updated SelectRows(), UpdateRow() and added SelectTable(),
* TruncateTable() and SQLVALUE constants for SQLValue()
* Oct 23, 2007 - Added QueryArray(), QuerySingleRow(), QuerySingleRowArray(),
* QuerySingleValue(), HasRecords(), AutoInsertUpdate()
* Oct 28, 2007 - Small bug fixes
* Nov 28, 2007 - Contribution from Douglas Gintz
* Jul 06, 2009 - GetXML() and GetJSON() contribution from Emre Erkan
* and ability to use a blank password if needed
*
* @example
* include("mysql.class.php");
*
* $db = new MySQL();
* $db = new MySQL(true, "database");
* $db = new MySQL(true, "database", "localhost", "username", "password");
*
*
* @category Ultimate MySQL Wrapper Class
* @package Ultimate MySQL Wrapper
* @version 2.5.1
* @author Jeff L. Williams
* @copyright 2007-2012 Jeff L. Williams
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link http://www.phpclasses.org/ultimatemysql Ultimate MySQL
*/
/**
* Ultimate MySQL Wrapper Class
*/
class MySQL
{
// SET THESE VALUES TO MATCH YOUR DATA CONNECTION
/** server name */
private $db_host = 'localhost';
/** user name */
private $db_user = '';
/** password */
private $db_pass = '';
/** database name */
private $db_dbname = '';
/** optional character set (i.e. utf8) */
private $db_charset = 'utf8';
/** optional character set collation (i.e. utf8_unicode_ci) */
private $db_charsetcollation = 'utf8_unicode_ci';
/** use persistent connection? */
private $db_pcon = false;
// constants for SQLValue function
const SQLVALUE_BIT = 'bit';
const SQLVALUE_BOOLEAN = 'boolean';
const SQLVALUE_DATE = 'date';
const SQLVALUE_DATETIME = 'datetime';
const SQLVALUE_NUMBER = 'number';
const SQLVALUE_ENUMERATE = 'enum';
const SQLVALUE_T_F = 't-f';
const SQLVALUE_TEXT = 'text';
const SQLVALUE_TIME = 'time';
const SQLVALUE_Y_N = 'y-n';
// class-internal variables - do not change
/** current row */
private $active_row = -1;
/** last mysql error string */
private $error_desc = '';
/** last mysql error number */
private $error_number = 0;
/** used for transactions */
private $in_transaction = false;
/** last id of record inserted */
private $last_insert_id;
/** last mysql query result */
private $last_result;
/** last mysql query */
private $last_sql = '';
/** mysql link resource */
private $mysql_link = 0;
/** holds the difference in time */
private $time_diff = 0;
/** start time for the timer */
private $time_start = 0;
/** tracks the number of queries executed through this instance */
private $query_count = 0;
/**
* Determines if an error throws an exception
*
* @api
* @var boolean Set to true to throw error exceptions
*/
public $ThrowExceptions = false;
/**
* Provide minimal or extended error information
*
* Determines if the code is running in a development or production environment: error diagnostics information
* is far more elaborate in a development environment setting to aid problem analysis and resolution.
*
* @api
* @var boolean Set to false to enable production environment behaviour (reduced info available for errors)
*/
public $InDevelopmentEnvironment = true;
/**
* Constructor: Opens the connection to the database
*
* @param boolean $connect (Optional) Auto-connect when object is created
* @param string $database (Optional) Database name
* @param string $server (Optional) Host address
* @param string $username (Optional) User name
* @param string $password (Optional) Password
* @param string $charset (Optional) Character set
* @param string $collation (Optional) Character set collation
*
* @example
* $db = new MySQL();
* $db = new MySQL(true, "database");
* $db = new MySQL(true, "database", "localhost", "username", "password");
*/
public function __construct($connect = true, $database = null, $server = null,
$username = null, $password = null, $charset = null,
$collation = null)
{
if ($database !== null) $this->db_dbname = $database;
if ($server !== null) $this->db_host = $server;
if ($username !== null) $this->db_user = $username;
if ($password !== null) $this->db_pass = $password;
if ($charset !== null) $this->db_charset = $charset;
if ($collation !== null) $this->db_charsetcollation = $collation;
if (strlen($this->db_host) > 0 &&
strlen($this->db_user) > 0)
{
if ($connect) $this->Open();
}
}
/**
* Destructor: Closes the connection to the database
*/
public function __destruct()
{
$this->Close();
}
/**
* UPSERT a row
*
* Automatically does an INSERT or UPDATE depending on whether a record
* already exists in a table.
*
* @api
* @param string $tableName The name of the table
* @param array $valuesArray An associative array containing the column
* names as keys and values as data. The values
* must be SQL ready (i.e. quotes around
* strings, formatted dates, etc.)
* @param array|string $whereArray An associative array containing the column
* names as keys and values as data. The values
* must be SQL ready (i.e. quotes around strings,
* formatted dates, etc.).
* <br/>
* This parameter may alternatively be a string, in
* which case it is used verbatim for the WHERE
* clause of the query. This is useful when
* advanced queries are constructed.
* @return boolean Returns TRUE on success or FALSE on error
*/
public function AutoInsertUpdate($tableName, $valuesArray, $whereArray)
{
if (!$this->SelectRows($tableName, $whereArray))
{
return false;
}
else if ($this->HasRecords())
{
return $this->UpdateRow($tableName, $valuesArray, $whereArray);
}
else
{
return $this->InsertRow($tableName, $valuesArray);
}
}
/**
* Test if the internal pointer is at the start of the record set
*
* Returns true if the internal pointer is at the beginning of the record set produced by the last query.
*
* @api
* @return boolean TRUE if at the first row or FALSE if not
*
* @example
* if ($db->BeginningOfSeek())
* {
* echo "We are at the beginning of the record set";
* }
*/
public function BeginningOfSeek()
{
$this->ResetError();
if ($this->IsConnected())
{
return ($this->active_row < 1);
}
else
{
return $this->SetError('No connection', -1);
}
}
/**
* Builds a comma delimited list of columns for use with a SQL query
*
* This method can be used to construct a SELECT, FROM or SORT BY section of an SQL query.
*
* @api
* @param array|string $columns Either an array containing the column names
* or a string. The latter is used when, for example,
* constructing 'advanced' queries with SUM(*)
* or other expressions in the SELECT fieldset section.
* @param boolean $addQuotes (Optional) TRUE to add quotes
* @param boolean $showAlias (Optional) TRUE to show column alias
* @param boolean $withSortMarker (Optional) TRUE when the field list is meant
* for an ORDER BY clause; fields may be prefixed by a
* plus(+) or minus(-) to indicate sort order.
* Default is ASCending for each field.
* @return string Returns the constructed SQL column list on success or NULL on failure
*/
public function BuildSQLColumns($columns, $addQuotes = true, $showAlias = true, $withSortMarker = false)
{
switch (gettype($columns))
{
case 'array':
$sql = '';
foreach ($columns as $key => $value)
{
$asc = '';
if ($withSortMarker)
{
switch ($value[0])
{
case '+':
$asc = ' ASC';
$value = substr($value, 1);
break;
case '-':
$asc = ' DESC';
$value = substr($value, 1);
break;
default:
$asc = ' ASC';
break;
}
}
// Build the columns
if (strlen($sql) != 0)
{
$sql .= ', ';
}
if ($addQuotes)
{
$sql .= self::SQLFixName($value);
}
else
{
$sql .= $value;
}
if ($showAlias && is_string($key) && (!empty($key)))
{
$sql .= ' AS ' . self::SQLFixName($key);
}
else if ($withSortMarker)
{
$sql .= $asc;
}
}
return $sql;
case 'string':
return $columns;
default:
return false;
}
}
/**
* Builds a SQL DELETE statement
*
* @api
* @param string $tableName The name of the table
* @param array|string $whereArray (Optional) An associative array containing the
* column names as keys and values as data. The
* values must be SQL ready (i.e. quotes around
* strings, formatted dates, etc.). If not specified
* then all values in the table are deleted.
* <br/>
* This parameter may alternatively be a string, in
* which case it is used verbatim for the WHERE
* clause of the query. This is useful when
* advanced queries are constructed.
* @return string Returns the SQL DELETE statement
*
* @example
* // Let's create an array for the example
* // $arrayVariable["column name"] = formatted SQL value
* $filter["ID"] = MySQL::SQLValue(7, MySQL::SQLVALUE_NUMBER);
* // Echo out the SQL statement
* echo MySQL::BuildSQLDelete("MyTable", $filter);
*/
public function BuildSQLDelete($tableName, $whereArray = null)
{
$sql = 'DELETE FROM ' . self::SQLFixName($tableName);
if (!is_null($whereArray))
{
$wh = $this->BuildSQLWhereClause($whereArray);
if (!is_string($wh)) return false;
$sql .= ' ' . $wh;
}
return $sql;
}
/**
* Builds a SQL INSERT statement
*
* @api
* @param string $tableName The name of the table
* @param array $valuesArray An associative array containing the column
* names as keys and values as data. The values
* must be SQL ready (i.e. quotes around
* strings, formatted dates, etc.)
* @return string Returns a SQL INSERT statement
*
* @example
* // Let's create an array for the example
* // $arrayVariable["column name"] = formatted SQL value
* $values["Name"] = MySQL::SQLValue("Violet");
* $values["Age"] = MySQL::SQLValue(777, MySQL::SQLVALUE_NUMBER);
* // Echo out the SQL statement
* echo MySQL::BuildSQLInsert("MyTable", $values);
*/
public function BuildSQLInsert($tableName, $valuesArray)
{
$columns = $this->BuildSQLColumns(array_keys($valuesArray), true, false);
$values = $this->BuildSQLColumns($valuesArray, false, false);
if (empty($columns) || empty($values)) return false;
$sql = 'INSERT INTO ' . self::SQLFixName($tableName) .
' (' . $columns . ') VALUES (' . $values . ')';
return $sql;
}
/**
* Builds a simple SQL SELECT statement
*
* @api
* @param string $tableName The name of the table
* @param array|string $whereArray (Optional) An associative array containing the
* column names as keys and values as data. The
* values must be SQL ready (i.e. quotes around
* strings, formatted dates, etc.)
* @param array|string $columns (Optional) The column or list of columns to select
* @param array|string $sortColumns (Optional) Column or list of columns to sort by.
* Column names may be prefixed by a plus(+) or minus(-)
* to indicate sort order.
* Default is ASCending for each column.
* @param integer|string $limit (Optional) The limit of rows to return
* @return string Returns a SQL SELECT statement
*
* @note Any of the parameters $whereArray, $columns, $sortColumns or $limit
* may alternatively be a string, in which case these are used verbatim
* in the query. This is useful when advanced queries are constructed.
*
* @example
* // Let's create an array for the example
* // $arrayVariable["column name"] = formatted SQL value
* $values["Name"] = MySQL::SQLValue("Violet");
* $values["Age"] = MySQL::SQLValue(777, MySQL::SQLVALUE_NUMBER);
* // Echo out the SQL statement
* echo MySQL::BuildSQLSelect("MyTable", $values);
*/
public function BuildSQLSelect($tableName, $whereArray = null, $columns = null,
$sortColumns = null, $limit = null)
{
if (!is_null($columns))
{
$sql = $this->BuildSQLColumns($columns);
if (!is_string($sql)) return false;
$sql = trim($sql);
}
if (empty($sql))
{
$sql = '*';
}
$sql = 'SELECT ' . $sql . ' FROM ' . $this->BuildSQLColumns($tableName);
if (!is_null($whereArray))
{
$wh = $this->BuildSQLWhereClause($whereArray);
if (!is_string($wh)) return false;
$sql .= ' ' . $wh;
}
if (!is_null($sortColumns))
{
$ordstr = $this->BuildSQLColumns($sortColumns, true, false, true);
if (!is_string($ordstr)) return false;
$ordstr = trim($ordstr);
if (!empty($ordstr))
{
$sql .= ' ORDER BY ' . $ordstr;
}
}
if (!is_null($limit))
{
if (1 == preg_match('/[^0-9 ,]/', $limit))
return $this->SetError('ERROR: Invalid LIMIT clause specified in BuildSQLSelect method.', -1);
$sql .= ' LIMIT ' . $limit;
}
return $sql;
}
/**
* Builds a SQL UPDATE statement
*
* @api
* @param string $tableName The name of the table
* @param array $valuesArray An associative array containing the column
* names as keys and values as data. The values
* must be SQL ready (i.e. quotes around
* strings, formatted dates, etc.)
* @param array|string $whereArray (Optional) An associative array containing the
* column names as keys and values as data. The
* values must be SQL ready (i.e. quotes around
* strings, formatted dates, etc.). If not specified
* then all values in the table are updated.
* <br/>
* This parameter may alternatively be a string, in
* which case it is used verbatim for the WHERE
* clause of the query. This is useful when
* advanced queries are constructed.
* @return string Returns a SQL UPDATE statement
*
* @example
* // Let's create two arrays for the example
* // $arrayVariable["column name"] = formatted SQL value
* $values["Name"] = MySQL::SQLValue("Violet");
* $values["Age"] = MySQL::SQLValue(777, MySQL::SQLVALUE_NUMBER);
* $filter["ID"] = MySQL::SQLValue(10, MySQL::SQLVALUE_NUMBER);
* // Echo out some SQL statements
* echo MySQL::BuildSQLUpdate("Test", $values, $filter)";
*/
public function BuildSQLUpdate($tableName, $valuesArray, $whereArray = null)
{
if (!is_array($valuesArray))
return $this->SetError('ERROR: Invalid valuesArray type specified in BuildSQLUpdate method', -1);
if (count($valuesArray) <= 0)
return $this->SetError('ERROR: Invalid/Empty valuesArray array specified in BuildSQLUpdate method', -1);
$sql = '';
foreach ($valuesArray as $key => $value)
{
if (empty($value) && !is_integer($value))
return $this->SetError('ERROR: Invalid value specified in BuildSQLUpdate method', -1);
if (empty($key))
return $this->SetError('ERROR: Invalid key specified in BuildSQLUpdate method', -1);
if (strlen($sql) != 0)
$sql .= ', ';
$sql .= self::SQLFixName($key) . ' = ' . $value;
}
$sql = 'UPDATE ' . self::SQLFixName($tableName) . ' SET ' . $sql;
if (!is_null($whereArray))
{
$wh = $this->BuildSQLWhereClause($whereArray);
if (!is_string($wh)) return false;
$sql .= ' ' . $wh;
}
return $sql;
}
/**
* Construct a value string suitable for incorporation anywhere
* in a SQL query. This method invokes self::SQLValue() under the hood.
*
* @static
* @api
* @param arbitrary $value The value to be checked and processed.
* Usually this would be a string, but any other
* type which can be cast to a string is fine
* as well.
* @return string Returns a string containing the SQL query ready value.
*/
static public function BuildSQLValue($value)
{
return self::SQLValue($value, gettype($value));
}
/**
* Builds a SQL WHERE clause from an array.
*
* If a key is specified, the key is used at the field name and the value
* as a comparison. If a key is not used, the value is used as the clause.
*
* @api
* @param array|string $whereArray An associative array containing the column
* names as keys and values as data. The values
* must be SQL ready (i.e. quotes around
* strings, formatted dates, etc.).
* <br/>
* This parameter may alternatively be a string, in
* which case it is returned verbatim. This is useful
* when advanced queries are constructed and this
* method is invoked internally.
* @return string Returns a string containing the SQL WHERE clause
*/
public function BuildSQLWhereClause($whereArray)
{
switch (gettype($whereArray))
{
case 'array':
$where = '';
foreach ($whereArray as $key => $value)
{
if (strlen($where) == 0)
{
$where = 'WHERE ';
}
else
{
$where .= ' AND ';
}
if (is_string($key) && empty($key))
return $this->SetError('ERROR: Invalid key specified in BuildSQLWhereClause method', -1);
if (empty($value) && !is_integer($value))
return $this->SetError('ERROR: Invalid value specified in BuildSQLWhereClause method for key ' . self::SQLFixName($key), -1);
if (is_string($key))
{
$where .= self::SQLFixName($key) . ' = ' . $value;
}
else
{
$where .= $value;
}
}
return $where;
case 'string':
return $whereArray;
default:
return $this->SetError('ERROR: Invalid key specified in BuildSQLWhereClause method', -1);
}
}
/**
* Close current MySQL connection
*
* @api
* @return object Returns TRUE on success or FALSE on error
*
* @example
* $db->Close();
*/
public function Close()
{
$this->ResetError();
$this->active_row = -1;
$success = $this->Release();
if ($success)
{
$success = @mysql_close($this->mysql_link);
if (!$success)
{
return $this->SetError();
}
else
{
unset($this->last_sql);
unset($this->last_result);
unset($this->mysql_link);
}
}
return $success;
}
/**
* Delete selected rows.
*
* Deletes rows in a table based on a WHERE filter
* (can be just one or many rows based on the filter).
*
* @api
* @param string $tableName The name of the table
* @param array|string $whereArray (Optional) An associative array containing the
* column names as keys and values as data. The
* values must be SQL ready (i.e. quotes around
* strings, formatted dates, etc.). If not specified
* then all values in the table are deleted.
* <br/>
* This parameter may alternatively be a string, in
* which case it is used verbatim for the WHERE
* clause of the query. This is useful when
* advanced queries are constructed.
* @return boolean Returns TRUE on success or FALSE on error
*
* @example
* // $arrayVariable["column name"] = formatted SQL value
* $filter["ID"] = 7;
*
* // Execute the delete
* $result = $db->DeleteRows("MyTable", $filter);
*
* // If we have an error
* if (!$result)
* {
* // Show the error and kill the script
* $db->Kill();
* }
*/
public function DeleteRows($tableName, $whereArray = null)
{
$this->ResetError();
if (!$this->IsConnected())
{
return $this->SetError('No connection', -1);
}
else
{
$sql = self::BuildSQLDelete($tableName, $whereArray);
if (!is_string($sql)) return false;
// Execute the UPDATE
return !!$this->Query($sql);
}
}
/**
* Returns true if the internal pointer is at the end of the records
*
* @api
* @return boolean TRUE if at the last row or FALSE if not
*
* @example
* if ($db->EndOfSeek())
* {
* echo "We are at the end of the record set";
* }
*/
public function EndOfSeek()
{
$this->ResetError();
if ($this->IsConnected())
{
return ($this->active_row >= $this->RowCount());
}
else
{
return $this->SetError('No connection', -1);
}
}
/**
* Return the last MySQL error as text
*
* @note
* The returned error description string is appended with the error number itself
* as ' (#<i>error_number</i>)'.
*
* @api
* @return string Error text from last known error
*
* @example
* if (!$db->Query("SELECT * FROM Table"))
* {
* echo $db->Error(); // Shows the error
* }
*
* if ($db->Error()) $db->Kill();
*/
public function Error()
{
$error = $this->error_desc;
if (empty($error))
{
if ($this->error_number <> 0)
{
$error = 'Unknown Error (#' . $this->error_number . ')';
}
else
{
$error = false;
}
}
else
{
if ($this->error_number > 0 || $this->error_number < -1)
{
$error .= ' (#' . $this->error_number . ')';
}
}
return $error;
}
/**
* Return the last MySQL error as a number
*
* @api
* @return integer Error number from last known error
*
* @example
* if ($db->ErrorNumber() <> 0)
* {
* $db->Kill(); // show the error message
* }
*/
public function ErrorNumber()
{
if (strlen($this->error_desc) > 0)
{
if ($this->error_number <> 0)
{
return $this->error_number;
}
else
{
return -1;
}
}
else
{
return $this->error_number;
}
}
/**
* Convert any value of any datatype into boolean (true or false)
*
* @static
* @api
* @param mixed $value Value to analyze for TRUE or FALSE
* @return boolean Returns TRUE or FALSE
*
* @example
* echo (MySQL::GetBooleanValue("Y") ? "True" : "False");
* echo (MySQL::GetBooleanValue("no") ? "True" : "False");
* echo (MySQL::GetBooleanValue("TRUE") ? "True" : "False");
* echo (MySQL::GetBooleanValue(1) ? "True" : "False");
*/
static public function GetBooleanValue($value)
{
if (gettype($value) == 'boolean')
{
return ($value == true);
}
elseif (is_numeric($value))
{
return (intval($value) > 0);
}
else
{
$cleaned = strtoupper(trim($value));
if ($cleaned == 'ON')
{
return true;
}
elseif ($cleaned == 'SELECTED' || $cleaned == 'CHECKED')
{
return true;
}
elseif ($cleaned == 'YES' || $cleaned == 'Y')
{
return true;
}
elseif ($cleaned == 'TRUE' || $cleaned == 'T')
{
return true;
}
else
{
return false;
}
}
}
/**
* Convert a string or integer value into a DateTime instance
*
* @static
* @api
* @param mixed $value Value to convert to a DateTime instance
* @return DateTime Returns the date/time encoded in the input $value on success; return a boolean FALSE on error.
*
* @example
* echo (MySQL::GetDateTimeValue("2010-01-31")->format('Y-m-d');
*/
static public function GetDateTimeValue($value)
{
if (gettype($value) == 'boolean')
{
return false;
}
elseif (is_numeric($value))
{
$date = new DateTime();
$date = $date->setTimestamp(intval($value));
}
else
{
$cleaned = trim($value);
$date = date_create($cleaned, new DateTimeZone('UTC'));
// apply some common sense: MySQL can spit out dates such as 0000-00-00 00:00:00, which are nonsensical
if (!empty($date) && $date->getTimestamp() === false)
{
return false;
}
}
return $date;
}
/**
* Return the comments for fields in a table
*
* @api
* @param string $table Table name
* @return array An array that contains the column comments
* or FALSE on error.
*
* @example
* $columns = $db->GetColumnComments("MyTable");
* foreach ($columns as $column => $comment)
* {
* echo $column . " = " . $comment . "<br />\n";
* }
*/
public function GetColumnComments($table)
{
$this->ResetError();
if (!$this->IsConnected())
{
return $this->SetError('No connection', -1);
}
$sql = 'SHOW FULL COLUMNS FROM ' . self::SQLFixName($table);
$this->last_sql = $sql;
$this->query_count++;
$records = mysql_query($sql, $this->mysql_link);
if (!$records)
{
return $this->SetError();
}
else
{
// Get the column names
$columnNames = $this->GetColumnNames($table);
if (!$columnNames)
{
return false;
}
else
{
$index = 0;
$columns = array();
// Fetches the array to be returned (column 8 is field comment):
while ($array_data = mysql_fetch_array($records, MYSQL_NUM))
{
$columns[$index] = $array_data[8];
$columns[$columnNames[$index++]] = $array_data[8];
}
return $columns;
}
}
}
/**
* Get the number of columns
*
* @api
* @param string $table (Optional) If a table name is not specified, the
* column count is returned from the last query
* @return integer The total count of columns or FALSE on error
*
* @example
* echo "Total Columns: " . $db->GetColumnCount("MyTable");
*/
public function GetColumnCount($table = null)
{
$this->ResetError();
if (!$this->IsConnected())
{
return $this->SetError('No connection', -1);
}
if (empty($table))
{
$result = mysql_num_fields($this->last_result);
if (!$result) return $this->SetError();
}
else
{
$sql = 'SELECT * FROM ' . self::SQLFixName($table) . ' LIMIT 1';
$this->last_sql = $sql;
$this->query_count++;
$records = mysql_query($sql, $this->mysql_link);
if (!$records)
{
return $this->SetError();
}
else
{
$result = mysql_num_fields($records);
if (!$result) return $this->SetError();
$success = @mysql_free_result($records);
if (!$success)
{
return $this->SetError();
}
}
}
return $result;
}
/**
* Return the data type for a specified column
*
* @api
* @param integer|string $column Column name or number (first column is 0)
* @param string $table (Optional) If a table name is not specified, the
* last returned records are used
* @return string The MySQL data (field) type. If the column does not
* exist or no records exist, return FALSE.
*
* @example
* echo "Type: " . $db->GetColumnDataType("FirstName", "Customer");
*/
public function GetColumnDataType($column, $table = null)
{
$this->ResetError();
if (!$this->IsConnected())
{
return $this->SetError('No connection', -1);
}
if (empty($table))
{
if ($this->RowCount() > 0)
{
if (is_numeric($column))
{
return mysql_field_type($this->last_result, $column);