Source for file mysqldb_class.php
Documentation is available at mysqldb_class.php
* Database Class provides a consistent API to communicate with MySQL or Oracle Databases.
* This one implements the MySQL API.
* Requires dbdefs.inc.php for global access data (user,pw,host,port,dbname,appname)
* @author Sascha 'SieGeL' Pfalz <php@saschapfalz.de>
* @version 0.39 (07-Aug-2010)
* $Id: mysqldb_class.php,v 1.25 2010/08/07 08:16:14 siegel Exp $
* @license http://opensource.org/licenses/bsd-license.php BSD License
define('DBOF_DEBUGOFF' , (1 <<
0));
define('DBOF_DEBUGSCREEN' , (1 <<
1));
* DEBUG: Debug to error_log()
define('DBOF_DEBUGFILE' , (1 <<
2));
* Connect and error handling (V0.28+).
* If DBOF_SHOW_NO_ERRORS is set and an error occures,
* the class still reports an an error of course but the error
* shown is reduced in informational details to avoid showing
* sensible informations in a productive environment.
* If DBOF_SHOW_ALL_ERRORS is set the maximum possible details are shown.
* Set RETURN_ALL_ERRORS if you want to handle errors yourself, in
* this case the class returns error codes if something goes wrong.
if(!defined('DBOF_SHOW_NO_ERRORS'))
define('DBOF_SHOW_NO_ERRORS' , 0);
define('DBOF_SHOW_ALL_ERRORS' , 1);
define('DBOF_RETURN_ALL_ERRORS' , 2);
* These defines are used in DescTable().
define('DBOF_MYSQL_COLNAME' , 0);
define('DBOF_MYSQL_COLTYPE' , 1);
define('DBOF_MYSQL_COLSIZE' , 2);
define('DBOF_MYSQL_COLFLAGS', 3);
/** @var mixed $sock Internal connection handle */
/** @var string $host Name of database to connect to */
/** @var integer $port Portnumber to use when connecting to MySQL */
/** @var string $user Name of database user used for connection */
/** @var string $pass Password of database user used for connection */
/** @var string $database Name of schema to be used */
/** @var integer $querycounter Counts the processed queries against the database */
/** @var float $querytime Contains the total SQL execution time in microseconds. */
/** @var string $appname Name of Application that uses this class */
/** @var string $classversion Version of this class in format VER.REV */
/** @var string $currentQuery Contains the actual query to be processed. */
/** @var integer $showError Flag indicates how the class should interact with errors */
/** @var integer $debug Flag indicates debug mode of class */
/** @var string $SAPI_type The SAPI type of php (used to detect CLI sapi) */
/** @var string $AdminEmail Email Address for the administrator of this project */
/** @var integer $myErrno Error code of last mysql operation (set in Print_Error()) */
/** @var string $myErrStr Error string of last mysql operation (set in Print_Error()) */
/** @var boolean $usePConnect TRUE = Connect() uses Persistant connection, else new one (Default) */
/** @var string $character_set Character set to use. */
/** @var string $locale Locale to use for DATE_FORMAT(), DAYNAME() and MONTHNAME() SQL functions. */
* @var boolean $new_link TRUE => Always create NEW connections, FALSE => Do not create new connections (default)
* @var integer $num_rows Number of rows returned from a previous SELECT/SHOW statement.
* Constructor of this class.
* The constructor takes default values from dbdefs.inc.php.
* Please see this file for further informations about the setable options.
* @param string $extconfig Optional other filename for dbdefs.inc.php, defaults to "dbdefs.inc.php".
require_once('dbdefs.inc.php');
$this->AdminEmail =
(isset
($_SERVER['SERVER_ADMIN'])) ?
$_SERVER['SERVER_ADMIN'] :
'';
$this->usePConnect =
FALSE; // Set to TRUE to use Persistant connections
$this->characterset =
''; // Will be filled from define MYSQLDB_CHARACTERSET during Connect()
$this->locale =
''; // Will be filled from define MYSQLDB_TIME_NAMES during Connect()
$this->new_link =
FALSE; // Same value as all previous releases, filled by MYSQLDB_NEW_LINK define
$this->num_rows =
0; // Number of rows returned from SELECT & SHOW statements.
$this->Print_Error('dbdefs.inc.php not found/wrong configured! Please check Class installation!');
if(defined('DB_ERRORMODE')) // You can set a default behavour for error handling in debdefs.inc.php
// Check if user requested persistant connection per default in dbdefs.inc.php
// Check if user wants to have set a specific character set with 'SET NAMES <cset>'
// Check if user wants to have set a specific locale with 'SET SET lc_time_names = <locale>;'
// Check if user defined a new behavour for NEW_LINK parameter in mysql_connect()
* Performs the connection to MySQL.
* If anything goes wrong calls Print_Error().
* You should set the defaults for your connection by setting
* user,pass,host and database in dbdefs.inc.php and leave
* connect() parameters empty.
* If MYSQLDB_CHARACTERSET define is set a "SET NAMES '<charset>'; is used straight after connecting.
* @param string $user Username used to connect to DB
* @param string $pass Password to use for given username
* @param string $host Hostname of database to connect to
* @param integer $port TCP port to use for connection. Defaults to 3306.
* @param string $db Schema to use on MySQL DB Server
* @return mixed Either the DB connection handle or NULL in case of an error.
function Connect($user=
'',$pass=
'',$host=
'',$db=
'',$port =
0)
$this->port =
MYSQLDB_PORT;
// Append port number ONLY if hostname doesn't start with a slash (which is a pipe!)
$this->printDebug('mysql_connect('.
sprintf("%s/%s@%s",$this->user,$this->pass,$this->host).
')');
else // Persistant connection requested:
$rc =
$this->Query("SET lc_time_names='".
$this->locale.
"'",MYSQL_NUM,1);
$this->Print_Error('Connect(): Error while trying to set lc_time_names to "'.
$this->locale.
'" !!!');
* Disconnects from MySQL.
* You may optionally pass an external link identifier.
* @param mixed $other_sock Optionally your own connection handle to close, else internal will be used
* Prints out MySQL Error in own <div> container and exits.
* Please note that this function does not return as long as you have not set DBOF_RETURN_ALL_ERRORS!
* @param string $ustr User-defined Error string to show
* @param mixed $var2dump Optionally a variable to print out with print_r()
$filename =
basename($_SERVER['SCRIPT_FILENAME']);
return($errnum); // Return the error number
echo
("<br>\n<div align=\"left\" style=\"background-color: #EEEEEE; color:#000000\" class=\"TB\">\n");
echo
("<font color=\"red\" face=\"Arial, Sans-Serif\"><b>".
$this->appname.
": Database Error occured!</b></font><br>\n<br>\n<code>\n");
echo
("\n!!! ".
$this->appname.
": Database Error occured !!!\n\n");
echo
($space.
"CODE: ".
$errnum.
$crlf);
echo
($space.
"DESC: ".
$errstr.
$crlf);
echo
($space.
"FILE: ".
$filename.
$crlf);
echo
($space.
"INFO: ".
$ustr.
$crlf);
echo
("<br>\nPlease inform <a href=\"mailto:".
$this->AdminEmail.
"\">".
$this->AdminEmail.
"</a> about this problem.");
echo
("<div align=\"right\"><small>PHP v".
phpversion().
" / MySQL Class v".
$this->classversion.
"</small></div>\n");
* Performs a single row query.
* Resflag can be MYSQL_NUM or MYSQL_ASSOC depending on what kind of array you want to be returned.
* Since v0.38 the value of mysql_num_rows() is stored in self::num_rows if the executed query was either a SELECT or a SHOW statement.
* @param string $querystring The query to be executed
* @param integer $resflag Decides how the result should be returned:
* - MYSQL_ASSOC = Data is returned as assoziative array
* - MYSQL_NUM = Data is returned as numbered array
* @param integer $no_exit Decides how the class should react on errors.
* If you set this to 1 the class won't automatically exit
* on an error but instead return the mysql_errno value.
* Default of 0 means that the class calls Print_Error()
* @return mixed Either the result of the query or an error code or no return value at all
* @see mysql_fetch_array()
* @see mysql_free_result()
function Query($querystring,$resflag =
MYSQL_ASSOC, $no_exit =
0)
return($this->Print_Error('Query(): No active Connection!',$querystring));
$no_exit =
1; // Override if user has set master define
return($this->Print_Error("Query('".
$querystring.
"') failed!"));
* Private function checks if a given query is not a DML command.
* Currently checks for SELECT,SHOW,EXPLAIN,DESCRIBE,OPTIMIZE,ANALYZE,CHECK
* commands, as these commands all can return a result set.
* @param string $querystring The query to check.
* @return bool Returns TRUE if query can return a result set, else returns FALSE for DML or other unknown commands (i.e. SET).
$querypart =
substr($querystring,0,10);
// Check if query requires returning the results or just the result of the query call:
if( StriStr($querypart,'SELECT ') ||
StriStr($querypart,'SHOW ') ||
StriStr($querypart,'EXPLAIN ') ||
StriStr($querypart,'DESCRIBE ') ||
StriStr($querypart,'OPTIMIZE ') ||
StriStr($querypart,'ANALYZE ') ||
StriStr($querypart,'CHECK ')
* Performs a multi-row query and returns result identifier.
* @param string $querystring The Query to be executed
* @param integer $no_exit The error indicator flag, can be one of:
* - 0 = (Default), In case of an error Print_Error is called and script terminates
* - 1 = In case of an error this function returns the error from mysql_errno()
* @return mixed A resource identifier or an errorcode (if $no_exit = 1)
return($this->Print_Error('QueryResult(): No active Connection!',$querystring));
return($this->Print_Error("QueryResult('".
$querystring.
"') failed!"));
* Fetches next row from result handle.
* Returns either numeric (MYSQL_NUM) or associative (MYSQL_ASSOC) array
* for one data row as pointed to by result var.
* @param mixed $result The resource identifier as returned by QueryResult()
* @param integer $resflag How you want the data to be returned:
* - MYSQL_ASSOC = Data is returned as assoziative array
* - MYSQL_NUM = Data is returned as numbered array
* @return array One row of the resulting query or NULL if there are no data anymore
* @see mysql_fetch_array()
return($this->Print_Error('FetchResult(): No valid result handle!'));
* Frees result returned by QueryResult().
* It is a good programming practise to give back what you have taken, so after processing
* your Multi-Row query with FetchResult() finally call this function to free the allocated
* @param mixed $result The resource identifier you want to be freed.
* @return mixed The resulting code of mysql_free_result (can be ignored).
* @see mysql_free_result()
* Returns MySQL Server Version.
* Opens an own connection if no active one exists.
* @return string MySQL Server Version
$ver =
$this->Query('SELECT VERSION()',MYSQL_NUM);
* Returns amount of queries executed by this class.
* @return integer Querycount
* Returns amount of time spend on queries executed by this class.
* @return float Time in seconds.msecs spent in executin MySQL code.
* Commits current transaction.
* Note: Requires transactional tables, else does nothing!
* Rollback current transaction.
* Note: Requires transactional tables, else does nothing!
$this->Query('ROLLBACK;');
* Function allows debugging of SQL Queries.
* $state can have these values:
* - DBOF_DEBUGOFF = Turn off debugging
* - DBOF_DEBUGSCREEN = Turn on debugging on screen (every Query will be dumped on screen)
* - DBOF_DEBUFILE = Turn on debugging on PHP errorlog
* You can mix the debug levels by adding the according defines!
* @param integer $state The DEBUG Level you want to be set
* Returns the current debug setting.
* @return integer The debug setting (bitmask)
* Handles output according to internal debug flag.
* @param string $msg The Text to be included in the debug message.
$formatstr =
"<div align=\"left\" style=\"background-color:#ffffff; color:#000000;\"><pre>DEBUG: %s</pre></div>\n";
$formatstr =
"DEBUG: %s\n";
* Returns version of this class.
* @return string The version of this class.
* Returns last used auto_increment id.
* @param mixed $extsock Optionally an external MySQL socket to use. If not given the internal socket is used.
* @return integer The last automatic insert id that was assigned by the MySQL server.
* Returns count of affected rows by last DML operation.
* @param mixed $extsock Optionally an external MySQL socket to use. If not given the internal socket is used.
* @return integer The number of affected rows by previous DML operation.
* @see mysql_affected_rows()
* Converts a MySQL default Datestring (YYYY-MM-DD HH:MI:SS) into a strftime() compatible format.
* You can use all format tags that strftime() supports, this function simply converts the mysql
* date string into a timestamp which is then passed to strftime together with your supplied
* format. The converted datestring is then returned.
* Please do not use this as default date converter, always use DATE_FORMAT() inside a query
* whenever possible as this is much faster than using this function! Only if you cannot use
* the MySQL SQL Date converting functions consider using this function.
* @param string $mysqldate The MySQL default datestring in format YYYY-MM-DD HH:MI:SS
* @param string $fmtstring A strftime() compatible format string.
* @return string The converted date string.
$dt =
explode(' ',$mysqldate); // Split in date/time
$dp =
explode('-',$dt[0]); // Split date
$tp =
explode(':',$dt[1]); // Split time
* Returns microtime in format s.mmmmm.
* Used to measure SQL execution time.
* @return float the current time in microseconds.
return ((float)
$usec + (float)
$sec);
* Allows to set the handling of errors.
* - DBOF_SHOW_NO_ERRORS => Show no security-relevant informations.
* - DBOF_SHOW_ALL_ERRORS => Show all errors (useful for develop).
* - DBOF_RETURN_ALL_ERRORS => No error/autoexit, just return the mysql_error code.
* @param integer $val The Error Handling mode you wish to use.
* @return integer The previous value for error handling.
* Returns current connection handle.
* Returns either the internal connection socket or -1 if no active handle exists.
* Useful if you want to work with mysql* functions in parallel to this class.
* @return mixed Internal socket value
* Allows to set internal socket to external value.
* @param mixed New socket handle to set (as returned from mysql_connect())
* Checks if we are already connected to our database.
* If not terminates by calling Print_Error().
return($this->Print_Error('<b>!!! NOT CONNECTED TO AN MYSQL DATABASE !!!</b>'));
* Send error email if programmer has defined a valid email address and
* enabled it with the define MYSQLDB_SENTMAILONERROR.
* @param integer $merrno MySQL errno number
* @param string $merrstr MySQL error description
* @param string $uerrstr User-supplied error description
$sname =
(isset
($_SERVER['SERVER_NAME'])) ?
$_SERVER['SERVER_NAME'] :
'';
$saddr =
(isset
($_SERVER['SERVER_ADDR'])) ?
$_SERVER['SERVER_ADDR'] :
'';
$raddr =
(isset
($_SERVER['REMOTE_ADDR'])) ?
$_SERVER['REMOTE_ADDR'] :
'';
$server=
$sname.
" (".
$saddr.
")";
$uagent =
(isset
($_SERVER['HTTP_USER_AGENT'])) ?
$_SERVER['HTTP_USER_AGENT'] :
'';
$message =
"MySQLDB Class v".
$this->classversion.
": Error occured on ".
date('r').
" !!!\n\n";
$message.=
" APPLICATION: ".
$this->appname.
"\n";
$message.=
" AFFECTED SERVER: ".
$server.
"\n";
$message.=
" USER AGENT: ".
$uagent.
"\n";
$message.=
" PHP SCRIPT: ".
$_SERVER['SCRIPT_FILENAME'].
"\n";
$message.=
" REMOTE IP ADDR: ".
$clientip.
"\n";
$message.=
" DATABASE DATA: ".
$this->user.
" @ ".
$this->host.
"\n";
$message.=
"SQL ERROR MESSAGE: ".
$merrstr.
"\n";
$message.=
" SQL ERROR CODE: ".
$merrno.
"\n";
$message.=
" INFOTEXT: ".
$uerrstr.
"\n";
$message.=
" SQL QUERY:\n";
$message.=
"------------------------------------------------------------------------------------\n";
$message.=
"------------------------------------------------------------------------------------\n";
if(defined('MYSQLDB_MAIL_EXTRAARGS') &&
MYSQLDB_MAIL_EXTRAARGS !=
'')
* Retrieve last mysql error number.
* @param mixed $other_sock Optionally your own connection handle to check, else internal will be used.
* @return integer The MySQL error number of the last operation.
* Retrieve last mysql error description.
* @param mixed $other_sock Optionally your own connection handle to check, else internal will be used.
* @return string The MySQL error description of the last operation.
* Sets connection behavour.
* If FALSE class uses mysql_connect to connect.
* If TRUE class uses mysql_pconnect to connect (Persistant connection).
* @param boolean The new setting for persistant connections.
* @return boolean The previous state.
* Escapes a given string with the 'mysql_real_escape_string' method.
* Always use this function to avoid SQL injections when adding dynamic data to MySQL!
* This function also handles the settings for magic_quotes_gpc/magic_quotes_sybase, if
* these settings are enabled this function uses stripslashes() first.
* @param string $str The string to escape.
* @return string The escaped string.
* Method to set the time_names setting of the MySQL Server.
* Pass it a valid locale string to change the locale setting of MySQL.
* Note that this is supported only since 5.0.25 of MySQL!
* @param string $locale A locale string for the language you want to set, i.e. 'de_DE'.
* @return integer 0 If an error occures or 1 if change was successful.
$rc =
$this->Query("SET lc_time_names='".
$locale.
"'",MYSQL_NUM,1);
$this->Print_Error('set_TimeNames(): Error while trying to set lc_time_names to "'.
$locale.
'" !!!');
* Method to return the current MySQL setting for the lc_time_names variable.
* @return string The current setting for the lc_time_names variable.
$data =
$this->Query("SELECT @@lc_time_names",MYSQL_NUM,1);
$this->Print_Error('get_TimeNames(): Error while trying to retrieve the lc_time_names variable !!!');
* Method to set the character set of the current connection.
* You must specify a valid character set name, else the class will report an error.
* See http://dev.mysql.com/doc/refman/5.0/en/charset-charsets.html for a list of supported character sets.
* @param string $charset The charset to set on the MySQL server side.
* @return integer 1 If all works, else 0 in case of an error.
$rc =
$this->Query("SET NAMES '".
$charset.
"'",MYSQL_NUM,1);
$this->Print_Error('set_Names(): Error while trying to perform SET NAMES "'.
$locale.
'" !!!');
* Method to return the current MySQL setting for the character_set variables.
* Note that MySQL returns a list of settings, so this method returns all character_set related
* settings as an associative array.
* @return array The current settings for the character_set variables.
$stmt =
$this->QueryResult("SHOW VARIABLES LIKE 'character_set%'",1);
* Returns the description for a given table.
* Array returned has the following fields:
* 3 => Field flags (like auto_increment).
* @param string $tname Name of table to describe.
* @return array Numerical array with all required table informations.
$this->PrintDebug('DescTable('.
$tname.
') called - Self-Connect: '.
$weopen);
for ($i =
0; $i <
$fields; $i++
)
* Function performs an insert statement from a given variable list.
* The insert statements will be constructed as NEW Insert style, and aligned to the "max_allowed_packet" boundary.
* This can dramatically improve bulk-inserts compared to fire every INSERT statement one by one.
* The array passed must be constructed with the keys defined as fieldnames and the values as the corresponding values.
* - $data[0]['fieldname1'] = 'wert0/1';
* - $data[0]['fieldname2'] = 'wert0/2';
* - $data[1]['fieldname1'] = 'wert1/2';
* - $data[1]['fieldname2'] = 'wert1/2';
* NOTE: Database must be connected!
* @param string $table_name Name of table to perform the insert against.
* @param array &$fields The associative array
* @param string $sql Either "INSERT" or "REPLACE", no other command is allowed here!
* @return array A numeric array with [0] => created query count, [1] => Querysize or FALSE in case of an error.
* @see examples/new_insert.php
if(StrToUpper($sql) !=
'INSERT' &&
StrToUpper($sql) !=
'REPLACE')
// First retrieve the max_allowed_packet size:
$d =
$this->Query("SHOW SESSION VARIABLES LIKE 'max_allowed_packet'");
$max_allowed_packet =
intval($d['Value']);
// Now start with the initial insert command:
$INSERT =
$sql.
' INTO '.
$table_name.
'(';
foreach($fields as $count =>
$data) break;
foreach($data as $fieldname =>
$fieldvalue)
foreach($fields as $count =>
$data)
foreach($data as $fieldname =>
$fieldvalue)
$buffer.=
$fieldvalue.
',';
if((strlen($query) +
strlen($buffer) +
2) <
$max_allowed_packet)
// Flush the current query, then append the new values and start again:
$rc =
$this->Query($query,MYSQL_ASSOC,1);
$query =
$INSERT.
$buffer;
// Also add of course the remaining data:
$rc =
$this->Query($query,MYSQL_ASSOC,1);
//printf("QUERIES GENERATED: %d - total size of all queries: %d\n",$qcount,$qsize);
return(array($qcount,$qsize));
* Returns the number of rows in the result set.
* Use this after a SELECT or SHOW etc. command has been executed.
* For DML operations like INSERT, UPDATE, DELETE the method AffectedRows() has to be used.
* @return integer Number of affected rows.
Documentation generated on Sat, 07 Aug 2010 10:18:23 +0200 by phpDocumentor 1.4.3