5 # A Simple SQL Database Abstraction Object 7 # Copyright 1999-2002 Axis Data 8 # This code is free software that can be used or redistributed under the 9 # terms of Version 2 of the GNU General Public License, as published by the 10 # Free Software Foundation (http://www.fsf.org). 12 # Author: Edward Almasy (almasy@axisdata.com) 14 # Part of the AxisPHP library v1.2.5 15 # For more information see http://www.axisdata.com/AxisPHP/ 25 # ---- PUBLIC INTERFACE -------------------------------------------------- 44 $UserName = NULL, $Password = NULL, $DatabaseName = NULL, $HostName = NULL)
46 # save DB access parameter values 47 $this->
DBUserName = $UserName ? $UserName : self::$GlobalDBUserName;
48 $this->DBPassword = $Password ? $Password : self::$GlobalDBPassword;
50 (isset(self::$GlobalDBHostName) ? self::$GlobalDBHostName
52 $this->
DBName = $DatabaseName ? $DatabaseName : self::$GlobalDBName;
54 # set memory threshold for cache clearing 55 if (!isset(self::$CacheMemoryThreshold))
57 self::$CacheMemoryThreshold = self::GetPhpMemoryLimit() / 4;
60 # if we don't already have a connection or DB access parameters were supplied 62 if (!array_key_exists($HandleIndex, self::$ConnectionHandles)
63 || $UserName || $Password || $DatabaseName || $HostName)
65 # open connection to DB server and select database 66 $this->Handle = self::ConnectAndSelectDB($this->
DBHostName,
68 self::$ConnectionHandles[$HandleIndex] = $this->Handle;
72 # set local connection handle 73 $this->Handle = self::$ConnectionHandles[$HandleIndex];
83 return array(
"DBUserName",
"DBPassword",
"DBHostName",
"DBName");
92 # if we don't already have a database server connection 94 if (!array_key_exists($HandleIndex, self::$ConnectionHandles))
96 # open connection to DB server and select database 97 $this->Handle = self::ConnectAndSelectDB($this->
DBHostName,
99 self::$ConnectionHandles[$HandleIndex] = $this->Handle;
103 # set local connection handle 104 $this->Handle = self::$ConnectionHandles[$HandleIndex];
117 $UserName, $Password, $HostName =
"localhost")
119 # save default DB access parameters 120 self::$GlobalDBUserName = $UserName;
121 self::$GlobalDBPassword = $Password;
122 self::$GlobalDBHostName = $HostName;
124 # clear any existing DB connection handles 125 self::$ConnectionHandles = array();
134 # save new default DB name 135 self::$GlobalDBName = $DatabaseName;
137 # clear any existing DB connection handles 138 self::$ConnectionHandles = array();
147 # choose config variable to use based on server version number 149 ?
"storage_engine" :
"default_storage_engine";
151 # set storage engine in database 152 $this->
Query(
"SET ".$ConfigVar.
" = ".$Engine);
163 # retrieve version string 164 $Version = $this->
Query(
"SELECT VERSION() AS ServerVer",
"ServerVer");
168 # strip off any build/config suffix 169 $Pieces = explode(
"-", $Version);
170 $Version = array_shift($Pieces);
173 # return version number to caller 187 return mysqli_get_client_info();
197 return mysqli_get_host_info($this->Handle);
237 public static function Caching($NewSetting = NULL)
239 # if cache setting has changed 240 if (($NewSetting !== NULL) && ($NewSetting != self::$CachingFlag))
243 self::$CachingFlag = $NewSetting;
245 # clear any existing cached results 246 self::$QueryResultCache = array();
249 # return current setting to caller 250 return self::$CachingFlag;
265 if ($NewSetting !== NULL)
267 self::$AdvancedCachingFlag = $NewSetting;
269 return self::$AdvancedCachingFlag;
293 if ($NormalizeWhitespace && ($ErrorsToIgnore !== NULL))
295 $RevisedErrorsToIgnore = array();
296 foreach ($ErrorsToIgnore as $SqlPattern => $ErrMsgPattern)
298 $SqlPattern = preg_replace(
"/\\s+/",
"\\s+", $SqlPattern);
299 $RevisedErrorsToIgnore[$SqlPattern] = $ErrMsgPattern;
301 $ErrorsToIgnore = $RevisedErrorsToIgnore;
303 $this->ErrorsToIgnore = $ErrorsToIgnore;
313 return $this->ErrorIgnored;
329 public function Query($QueryString, $FieldName =
"")
331 # clear flag that indicates whether query error was ignored 332 $this->ErrorIgnored = FALSE;
334 # if caching is enabled 335 if (self::$CachingFlag)
337 # if SQL statement is read-only 338 if ($this->IsReadOnlyStatement($QueryString))
340 # if we have statement in cache 341 if (isset(self::$QueryResultCache[$QueryString][
"NumRows"]))
343 if (self::$QueryDebugOutputFlag)
344 { print(
"DB-C: $QueryString<br>\n"); }
346 # make sure query result looks okay 347 $this->QueryHandle = TRUE;
349 # increment cache hit counter 350 self::$CachedQueryCounter++;
352 # make local copy of results 353 $this->QueryResults = self::$QueryResultCache[$QueryString];
354 $this->NumRows = self::$QueryResultCache[$QueryString][
"NumRows"];
356 # set flag to indicate that results should be retrieved from cache 357 $this->GetResultsFromCache = TRUE;
361 # execute SQL statement 362 $this->QueryHandle = $this->RunQuery($QueryString);
363 if (!$this->QueryHandle instanceof mysqli_result) {
return FALSE; }
365 # save number of rows in result 366 $this->NumRows = mysqli_num_rows($this->QueryHandle);
368 # if too many rows to cache 369 if ($this->NumRows >= self::$CacheRowsThreshold)
371 # set flag to indicate that query results should not 372 # be retrieved from cache 373 $this->GetResultsFromCache = FALSE;
377 # if we are low on memory 378 if (self::GetFreeMemory() < self::$CacheMemoryThreshold)
380 # clear out all but last few rows from cache 381 self::$QueryResultCache = array_slice(
382 self::$QueryResultCache,
383 (0 - self::$CacheRowsToLeave));
386 # if advanced caching is enabled 387 if (self::$AdvancedCachingFlag)
389 # save tables accessed by query 390 self::$QueryResultCache[$QueryString][
"TablesAccessed"] =
391 $this->TablesAccessed($QueryString);
395 if ($this->NumRows > 0)
398 for ($Row = 0; $Row < $this->NumRows; $Row++)
400 $this->QueryResults[$Row] =
401 mysqli_fetch_assoc($this->QueryHandle);
404 # cache query results 405 self::$QueryResultCache[$QueryString] = $this->QueryResults;
409 # clear local query results 410 unset($this->QueryResults);
413 # cache number of rows 414 self::$QueryResultCache[$QueryString][
"NumRows"] = $this->NumRows;
416 # set flag to indicate that query results should be 417 # retrieved from cache 418 $this->GetResultsFromCache = TRUE;
424 # if advanced caching is enabled 425 if (self::$AdvancedCachingFlag)
427 # if table modified by statement is known 428 $TableModified = $this->TableModified($QueryString);
431 # for each cached query 432 foreach (self::$QueryResultCache
433 as $CachedQueryString => $CachedQueryResult)
435 # if we know what tables were accessed 436 if ($CachedQueryResult[
"TablesAccessed"])
438 # if tables accessed include the one we may modify 439 if (in_array($TableModified,
440 $CachedQueryResult[
"TablesAccessed"]))
442 # clear cached query results 443 unset(self::$QueryResultCache[$CachedQueryString]);
448 # clear cached query results 449 unset(self::$QueryResultCache[$CachedQueryString]);
455 # clear entire query result cache 456 self::$QueryResultCache = array();
461 # clear entire query result cache 462 self::$QueryResultCache = array();
465 # execute SQL statement 466 $this->QueryHandle = $this->RunQuery($QueryString);
467 if ($this->QueryHandle === FALSE) {
return FALSE; }
469 # set flag to indicate that query results should not be 470 # retrieved from cache 471 $this->GetResultsFromCache = FALSE;
475 $this->RowCounter = 0;
477 # increment query counter 478 self::$QueryCounter++;
482 # execute SQL statement 483 $this->QueryHandle = $this->RunQuery($QueryString);
484 if ($this->QueryHandle === FALSE) {
return FALSE; }
487 if (($FieldName !=
"") && ($this->QueryHandle !== FALSE))
493 return $this->QueryHandle;
512 $FHandle = fopen($FileName,
"r");
514 # if file open succeeded 515 if ($FHandle !== FALSE)
517 # while lines left in file 520 while (!feof($FHandle))
522 # read in line from file 523 $Line = fgets($FHandle, 32767);
525 # trim whitespace from line 528 # if line is not empty and not a comment 529 if (!preg_match(
"/^#/", $Line)
530 && !preg_match(
"/^--/", $Line)
533 # add line to current query 536 # if line completes a query 537 if (preg_match(
"/;$/", $Line))
541 $Result = $this->
Query($Query);
544 # if query resulted in an error that is not ignorable 545 if ($Result === FALSE)
547 # stop processing queries and set error code 559 # return number of executed queries to caller 570 return $this->ErrMsg;
591 if ($NewValue !== NULL) { self::$DisplayErrors = $NewValue; }
592 return self::$DisplayErrors;
601 # if caching is enabled and query was cached 602 if (self::$CachingFlag && $this->GetResultsFromCache)
604 # return cached number of rows to caller 605 return $this->NumRows;
609 # call to this method after an unsuccessful query 610 if (!$this->QueryHandle instanceof mysqli_result)
615 # retrieve number of rows and return to caller 616 return mysqli_num_rows($this->QueryHandle);
627 # call to this method after an unsuccessful query 628 if (!$this->QueryHandle instanceof mysqli_result)
633 # retrieve number of rows and return to caller 634 return mysqli_affected_rows($this->Handle);
644 # if caching is enabled and query was cached 645 if (self::$CachingFlag && $this->GetResultsFromCache)
647 # if rows left to return 648 if ($this->RowCounter < $this->NumRows)
650 # retrieve row from cache 651 $Result = $this->QueryResults[$this->RowCounter];
653 # increment row counter 664 # call to this method after successful query 665 if ($this->QueryHandle instanceof mysqli_result)
667 $Result = mysqli_fetch_assoc($this->QueryHandle);
668 if ($Result === NULL) { $Result = FALSE; }
671 # call to this method after unsuccessful query 678 # return row to caller 690 # assume no rows will be returned 693 # for each available row 695 while ((($RowsFetched < $NumberOfRows) || ($NumberOfRows == NULL))
703 # return array of rows to caller 728 if ($IndexFieldName != NULL)
730 $Array[$Record[$IndexFieldName]] = $Record[$FieldName];
734 $Array[] = $Record[$FieldName];
751 return isset($Record[$FieldName]) ? $Record[$FieldName] : NULL;
762 return (
int)$this->
Query(
763 "SELECT LAST_INSERT_ID() AS InsertId",
782 $TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
784 # expand condition if supplied 785 if ($Condition != NULL) { $Condition =
" WHERE ".$Condition; }
787 # read cached record from database if not already loaded 788 if (!isset($CachedRecord))
790 $this->
Query(
"SELECT * FROM `".$TableName.
"` ".$Condition);
794 # if new value supplied 797 # update value in database 798 $this->
Query(
"UPDATE `".$TableName.
"` SET `".$FieldName.
"` = " 799 .(($NewValue === NULL) ?
"NULL" :
"'" 800 .mysqli_real_escape_string($this->Handle, $NewValue).
"'")
803 # update value in cached record 804 $CachedRecord[$FieldName] = $NewValue;
807 # return value from cached record to caller 808 return isset($CachedRecord[$FieldName])
809 ? $CachedRecord[$FieldName] : NULL;
829 $TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
833 $Condition, $CachedRecord);
853 $TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
857 $Condition, $CachedRecord);
871 public function CopyValues($TableName, $IdColumn, $SrcId, $DstId,
872 $ColumnsToExclude = array())
874 # retrieve names of all columns in table 877 # remove columns to be excluded from copy 878 $ColumnsToExclude[] = $IdColumn;
879 $ColumnsToCopy = array_diff($AllColumns, $ColumnsToExclude);
881 # normalize destination IDs 882 $DstIds = is_array($DstId) ? $DstId : array($DstId);
883 $DstIds = array_diff($DstIds, array($SrcId));
885 # if there are columns to copy and we have destinations 886 if (count($ColumnsToCopy) && count($DstIds))
888 # construct and execute query to perform copy 889 $Query =
"UPDATE `".$TableName.
"` AS Target" 890 .
" LEFT JOIN `".$TableName.
"` AS Source" 891 .
" ON Source.`".$IdColumn.
"` = '".addslashes($SrcId).
"'";
892 $QuerySets = array();
893 foreach ($ColumnsToCopy as $ColumnName)
895 $QuerySets[] =
"Target.`".$ColumnName.
"` = Source.`".$ColumnName.
"`";
897 $Query .=
" SET ".implode(
", ", $QuerySets);
898 $QueryConditions = array();
899 foreach ($DstIds as $Id)
901 $QueryConditions[] =
"Target.`".$IdColumn.
"` = '".addslashes($DstId).
"'";
903 $Query .=
" WHERE ".implode(
" OR ", $QueryConditions);
904 $this->
Query($Query);
921 return mysqli_real_escape_string($this->Handle, $String);
932 $this->
Query(
"-- ".$String);
942 $this->
Query(
"SHOW TABLES LIKE '".addslashes($TableName).
"'");
954 $this->
Query(
"DESC ".$TableName);
955 while ($CurrentFieldName = $this->
FetchField(
"Field"))
957 if ($CurrentFieldName == $FieldName) {
return TRUE; }
970 $this->
Query(
"DESC ".$TableName);
972 return $AllTypes[$FieldName];
982 $this->
Query(
"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS" 983 .
" WHERE TABLE_SCHEMA = '".addslashes($this->
DBName)
984 .
"' AND TABLE_NAME = '".addslashes($TableName).
"'");
995 self::$QueryDebugOutputFlag = $NewSetting;
1005 return self::$QueryCounter;
1016 return self::$CachedQueryCounter;
1026 if (self::$QueryCounter)
1028 return (self::$CachedQueryCounter / self::$QueryCounter) * 100;
1038 # ---- PRIVATE INTERFACE ------------------------------------------------- 1046 private $QueryHandle;
1047 private $QueryResults;
1048 private $RowCounter;
1050 private $GetResultsFromCache;
1051 private $ErrorIgnored = FALSE;
1052 private $ErrorsToIgnore = NULL;
1053 private $ErrMsg = NULL;
1054 private $ErrNo = NULL;
1056 private static $DisplayErrors = FALSE;
1058 private static $GlobalDBUserName;
1059 private static $GlobalDBPassword;
1060 private static $GlobalDBHostName;
1061 private static $GlobalDBName;
1064 private static $QueryDebugOutputFlag = FALSE;
1065 # flag for whether caching is turned on 1066 private static $CachingFlag = TRUE;
1067 # query result advanced caching flag 1068 private static $AdvancedCachingFlag = FALSE;
1069 # global cache for query results 1070 private static $QueryResultCache = array();
1072 private static $QueryCounter = 0;
1073 private static $CachedQueryCounter = 0;
1074 # database connection link handles 1075 private static $ConnectionHandles = array();
1076 # do not cache queries that return more than this number of rows 1077 private static $CacheRowsThreshold = 250;
1078 # prune the query cache if there is less than this amount of memory free 1079 private static $CacheMemoryThreshold;
1080 # number of rows to leave in cache when pruning 1081 private static $CacheRowsToLeave = 10;
1082 # number of retry attempts to make to connect to database 1083 private static $ConnectRetryAttempts = 3;
1084 # number of seconds to wait between connection retry attempts 1085 private static $ConnectRetryInterval = 5;
1087 # server connection error codes 1089 # through socket '%s
' (%d) 1090 const CR_CONN_HOST_ERROR = 2003; # Can't connect to MySQL server on
'%s' (%d)
1094 # connection error codes that may be recoverable 1095 private static $RecoverableConnectionErrors = array(
1096 self::CR_CONNECTION_ERROR,
1109 private static function ConnectAndSelectDB(
1112 $ConnectAttemptsLeft = self::$ConnectRetryAttempts + 1;
1115 # if this is not our first connection attempt 1118 # wait for the retry interval 1119 sleep(self::$ConnectRetryInterval);
1122 # attempt to connect to server 1124 $ConnectAttemptsLeft--;
1126 # repeat if we do not have a connection and there are retry attempts 1127 # left and the connection error code indicates a retry may succeed 1130 while (!$Handle && $ConnectAttemptsLeft
1131 && in_array(mysqli_connect_errno(),
1132 self::$RecoverableConnectionErrors));
1135 # throw exception if connection attempts failed 1138 throw new Exception(
"Could not connect to database: " 1139 .mysqli_connect_error().
" (errno: ".mysqli_connect_errno().
")");
1143 $Result = mysqli_select_db($Handle,
$DBName);
1144 if ($Result !== TRUE)
1146 throw new Exception(
"Could not select database: " 1147 .mysqli_error($Handle).
" (errno: ".mysqli_errno($Handle).
")");
1150 # return new connection to caller 1159 private function IsReadOnlyStatement($QueryString)
1161 return preg_match(
"/^[ ]*SELECT /i", $QueryString) ? TRUE : FALSE;
1170 private function TableModified($QueryString)
1172 # assume we're not going to be able to determine table 1175 # split query into pieces 1176 $QueryString = trim($QueryString);
1177 $Words = preg_split(
"/\s+/", $QueryString);
1179 # if INSERT statement 1181 if (strtoupper($Words[0]) ==
"INSERT")
1183 # skip over modifying keywords 1184 while ((strtoupper($Words[$WordIndex]) ==
"LOW_PRIORITY")
1185 || (strtoupper($Words[$WordIndex]) ==
"DELAYED")
1186 || (strtoupper($Words[$WordIndex]) ==
"IGNORE")
1187 || (strtoupper($Words[$WordIndex]) ==
"INTO"))
1192 # next word is table name 1193 $TableName = $Words[$WordIndex];
1195 # else if UPDATE statement 1196 elseif (strtoupper($Words[0]) ==
"UPDATE")
1198 # skip over modifying keywords 1199 while ((strtoupper($Words[$WordIndex]) ==
"LOW_PRIORITY")
1200 || (strtoupper($Words[$WordIndex]) ==
"IGNORE"))
1205 # if word following next word is SET 1206 if (strtoupper($Words[$WordIndex + 1]) ==
"SET")
1208 # next word is table name 1209 $TableName = $Words[$WordIndex];
1212 # else if DELETE statement 1213 elseif (strtoupper($Words[0]) ==
"DELETE")
1215 # skip over modifying keywords 1216 while ((strtoupper($Words[$WordIndex]) ==
"LOW_PRIORITY")
1217 || (strtoupper($Words[$WordIndex]) ==
"IGNORE")
1218 || (strtoupper($Words[$WordIndex]) ==
"QUICK"))
1223 # if next term is FROM 1224 if (strtoupper($Words[$WordIndex]) ==
"FROM")
1226 # next word is table name 1228 $TableName = $Words[$WordIndex];
1232 # discard table name if it looks at all suspicious 1235 if (!preg_match(
"/[a-zA-Z0-9]+/", $TableName))
1241 # return table name (or lack thereof) to caller 1251 private function TablesAccessed($QueryString)
1253 # assume we're not going to be able to determine tables 1254 $TableNames = FALSE;
1256 # split query into pieces 1257 $QueryString = trim($QueryString);
1258 $Words = preg_split(
"/\s+/", $QueryString);
1259 $UQueryString = strtoupper($QueryString);
1260 $UWords = preg_split(
"/\s+/", $UQueryString);
1262 # if SELECT statement 1263 if ($UWords[0] ==
"SELECT")
1265 # keep going until we hit FROM or last word 1267 while (($UWords[$WordIndex] !=
"FROM")
1268 && strlen($UWords[$WordIndex]))
1274 if ($UWords[$WordIndex] ==
"FROM")
1276 # for each word after FROM 1278 while (strlen($UWords[$WordIndex]))
1280 # if current word ends with comma 1281 if (preg_match(
"/,$/", $Words[$WordIndex]))
1283 # strip off comma and add word to table name list 1284 $TableNames[] = substr($Words[$WordIndex], 0, -1);
1288 # add word to table name list 1289 $TableNames[] = $Words[$WordIndex];
1291 # if next word is not comma 1293 if ($Words[$WordIndex] !=
",")
1295 # if word begins with comma 1296 if (preg_match(
"/^,/", $Words[$WordIndex]))
1298 # strip off comma (NOTE: modifies $Words array!) 1299 $Words[$WordIndex] = substr($Words[$WordIndex], 1);
1301 # decrement index so we start with this word next pass 1306 # stop scanning words (non-basic JOINs not yet handled) 1318 # discard table names if they look at all suspicious 1321 foreach ($TableNames as $Name)
1323 if (!preg_match(
"/^[a-zA-Z0-9]+$/", $Name))
1325 $TableNames = FALSE;
1331 # return table name (or lack thereof) to caller 1341 private function RunQuery($QueryString)
1343 # log query start time if debugging output is enabled 1344 if (self::$QueryDebugOutputFlag) { $QueryStartTime = microtime(TRUE); }
1346 # run query against database 1347 $this->QueryHandle = mysqli_query($this->Handle, $QueryString) ;
1349 # print query and execution time if debugging output is enabled 1350 if (self::$QueryDebugOutputFlag)
1352 print
"DB: ".$QueryString.
" [" 1353 .sprintf(
"%.2f", microtime(TRUE) - $QueryStartTime)
1357 # if query failed and there are errors that we can ignore 1358 if (($this->QueryHandle === FALSE) && $this->ErrorsToIgnore)
1360 # for each pattern for an error that we can ignore 1361 foreach ($this->ErrorsToIgnore as $SqlPattern => $ErrMsgPattern)
1363 # if error matches pattern 1364 $ErrorMsg = mysqli_error($this->Handle);
1365 if (preg_match($SqlPattern, $QueryString)
1366 && preg_match($ErrMsgPattern, $ErrorMsg))
1368 # set return value to indicate error was ignored 1369 $this->QueryHandle = TRUE;
1371 # set internal flag to indicate that an error was ignored 1372 $this->ErrorIgnored = $ErrorMsg;
1374 # stop looking at patterns 1381 if ($this->QueryHandle === FALSE)
1383 # clear stored value for number of rows retrieved 1386 # retrieve error info 1387 $this->ErrMsg = mysqli_error($this->Handle);
1388 $this->ErrNo = mysqli_errno($this->Handle);
1390 # if we are supposed to be displaying errors 1391 if (self::$DisplayErrors)
1394 print(
"<b>SQL Error:</b> <i>".$this->ErrMsg
1395 .
"</i> (".$this->ErrNo.
")<br/>\n");
1396 print(
"<b>SQL Statement:</b> <i>" 1397 .htmlspecialchars($QueryString).
"</i><br/>\n");
1399 # retrieve execution trace that got us to this point 1400 $Trace = debug_backtrace();
1402 # remove current context from trace 1403 array_shift($Trace);
1405 # make sure file name and line number are available 1406 foreach ($Trace as $Index => $Loc)
1408 if (!array_key_exists(
"file", $Loc))
1410 $Trace[$Index][
"file"] =
"UNKNOWN";
1412 if (!array_key_exists(
"line", $Loc))
1414 $Trace[$Index][
"line"] =
"??";
1418 # determine length of leading path common to all file names in trace 1420 $OurFile = __FILE__;
1422 foreach ($Trace as $Loc)
1424 if ($Loc[
"file"] !=
"UNKNOWN")
1427 $FNameLength = strlen($Loc[
"file"]);
1428 while ($Index < $FNameLength &&
1429 $Loc[
"file"][$Index] == $OurFile[$Index])
1431 $PrefixLen = min($PrefixLen, $Index);
1435 foreach ($Trace as $Loc)
1439 foreach ($Loc[
"args"] as $Arg)
1442 switch (gettype($Arg))
1445 $ArgString .= $Arg ?
"TRUE" :
"FALSE";
1454 $ArgString .=
'"<i>'.htmlspecialchars(substr($Arg, 0, 40))
1455 .((strlen($Arg) > 40) ?
"..." :
"").
'</i>"';
1461 $ArgString .= strtoupper(gettype($Arg));
1465 $ArgString .= get_class($Arg);
1468 case "unknown type":
1469 $ArgString .=
"UNKNOWN";
1474 $Loc[
"file"] = substr($Loc[
"file"], $PrefixLen);
1475 $LocString .=
" ";
1476 if (array_key_exists(
"class", $Loc))
1477 { $LocString .= $Loc[
"class"].
"::"; }
1478 $LocString .= $Loc[
"function"].
"(".$ArgString.
")" 1479 .
" - ".$Loc[
"file"].
":".$Loc[
"line"]
1482 print(
"<b>Trace:</b><br>\n".$LocString);
1485 return $this->QueryHandle;
1492 static private function GetPhpMemoryLimit()
1494 $Str = strtoupper(ini_get(
"memory_limit"));
1495 if (substr($Str, -1) ==
"B") { $Str = substr($Str, 0, strlen($Str) - 1); }
1496 switch (substr($Str, -1))
1499 $MemoryLimit = (int)$Str * 1024;
1503 $MemoryLimit = (int)$Str * 1048576;
1507 $MemoryLimit = (int)$Str * 1073741824;
1511 $MemoryLimit = (int)$Str;
1514 return $MemoryLimit;
1521 static private function GetFreeMemory()
1523 return self::GetPhpMemoryLimit() - memory_get_usage();
1527 # define return values (numerical values correspond to MySQL error codes) 1529 define(
"DB_OKAY", 0);
1530 define(
"DB_ERROR", 1);
1531 define(
"DB_ACCESSDENIED", 2);
1532 define(
"DB_UNKNOWNDB", 3);
1533 define(
"DB_UNKNOWNTABLE", 4);
1534 define(
"DB_SYNTAXERROR", 5);
1535 define(
"DB_DBALREADYEXISTS", 6);
1536 define(
"DB_DBDOESNOTEXIST", 7);
1537 define(
"DB_DISKFULL", 8);
1540 # define value to designate omitted arguments (so DB values can be set to NULL) 1541 define(
"DB_NOVALUE",
"!-_-_-DB_NOVALUE-_-_-!");
1543 # MySQL error code mapping 1554 # date() format for SQL dates 1555 define(
"DATE_SQL",
"Y-m-d H:i:s");
QueryErrMsg()
Get most recent error message text set by Query().
static Caching($NewSetting=NULL)
Get or set whether query result caching is currently enabled.
GetServerVersion($FullVersion=FALSE)
Get database server version number.
static SetGlobalDatabaseName($DatabaseName)
Set default database name.
const CR_CONNECTION_ERROR
SetDefaultStorageEngine($Engine)
Set default database storage engine.
ExecuteQueriesFromFile($FileName)
Execute queries from specified file.
UpdateIntValue($TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
A convenience function to get or set an integer value in the database.
SQL database abstraction object with smart query caching.
SetQueryErrorsToIgnore($ErrorsToIgnore, $NormalizeWhitespace=TRUE)
Set query errors to ignore.
const CR_SERVER_GONE_ERROR
DBUserName()
Get name used to connect with database server.
EscapeString($String)
Escape a string that may contain null bytes.
FetchRow()
Get next database row retrieved by most recent query.
LastInsertId()
Get ID of row added by the last SQL "INSERT" statement.
__construct($UserName=NULL, $Password=NULL, $DatabaseName=NULL, $HostName=NULL)
Object constructor.
TableExists($TableName)
Get whether specified table exists.
static SetGlobalServerInfo($UserName, $Password, $HostName="localhost")
Set default login and host info for database server.
GetClientVersion()
Get version number of the client libraries being used to connect to the database server (Currently th...
GetFieldType($TableName, $FieldName)
Get field (column) type.
NumRowsSelected()
Get number of rows returned by last SELECT or SHOW query.
FetchRows($NumberOfRows=NULL)
Get specified number of database rows retrieved by most recent query.
static QueryDebugOutput($NewSetting)
Enable or disable debugging output for queries.
Query($QueryString, $FieldName="")
Query database (with caching if enabled).
GetColumns($TableName)
Get column (database field) names.
FetchField($FieldName)
Pull next row from last DB query and get a specific value from that row.
FieldExists($TableName, $FieldName)
Get whether specified field exists in specified table.
static NumCacheHits()
Get the number of queries that have resulted in cache hits since program execution began...
FetchColumn($FieldName, $IndexFieldName=NULL)
Get all available values for specified database field retrieved by most recent query.
DBHostName()
Get host name of system on which database server resides.
NumRowsAffected()
Get number of rows affected by last INSERT, UPDATE, REPLACE, or DELETE query.
UpdateFloatValue($TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
A convenience function to get or set a float value in the database.
QueryErrNo()
Get most recent error code set by Query().
GetHostInfo()
Get database connection type and hostname.
UpdateValue($TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
A convenience function to get or set a value in the database.
static AdvancedCaching($NewSetting=NULL)
Get or set whether advanced query result cachine is currently enabled.
static DisplayQueryErrors($NewValue=NULL)
Get/set whether Query() errors will be displayed.
static CacheHitRate()
Get the ratio of query cache hits to queries as a percentage.
IgnoredError()
Check whether an error was ignored by the most recent query.
DBName()
Get current database name.
CopyValues($TableName, $IdColumn, $SrcId, $DstId, $ColumnsToExclude=array())
A convenience function to copy values from one row to another.
LogComment($String)
Peform query that consists of SQL comment statement.
__wakeup()
Restore database connection when unserialized.
static NumQueries()
Get the number of queries that have been run since program execution began.