Class db_MySQL

Description

Main class definition.

Located in /mysqldb_class.php (line 71)


	
			
Variable Summary
string $AdminEmail
string $appname
string $characterset
string $classversion
string $currentQuery
string $database
integer $debug
string $host
string $locale
integer $myErrno
string $myErrStr
boolean $new_link
integer $num_rows
string $pass
integer $port
integer $querycounter
float $querytime
string $SAPI_type
integer $showError
mixed $sock
boolean $usePConnect
string $user
Method Summary
db_MySQL db_MySQL ([string $extconfig = ''])
integer AffectedRows ([mixed $extsock = -1])
void checkSock ()
void Commit ()
mixed Connect ([string $user = ''], [string $pass = ''], [string $host = ''], [string $db = ''], [integer $port = 0])
string ConvertMySQLDate (string $mysqldate, string $fmtstring)
array DescTable (string $tname)
void Disconnect ([mixed $other_sock = -1])
string EscapeString (string $str)
array FetchResult (mixed $result, [integer $resflag = MYSQL_ASSOC])
mixed FreeResult (mixed $result)
string GetClassVersion ()
integer GetDebug ()
integer GetErrno ([mixed $other_sock = -1])
string GetErrorText ([mixed $other_sock = -1])
float getmicrotime ()
integer GetQueryCount ()
float GetQueryTime ()
array get_CharSet ()
string get_TimeNames ()
bool IsQueryWithResult (string $querystring)
integer LastInsertId ([mixed $extsock = -1])
integer NumRows ()
array PerformNewInsert (string $table_name, array &$fields, [string $sql = 'INSERT'])
void PrintDebug (string $msg)
void Print_Error ([string $ustr = ""], [mixed $var2dump = ""])
mixed Query (string $querystring, [integer $resflag = MYSQL_ASSOC], [integer $no_exit = 0])
mixed QueryResult (string $querystring, [integer $no_exit = 0])
void Rollback ()
void SendMailOnError (integer $merrno, string $merrstr, string $uerrstr)
void SetConnectionHandle (mixed $extsock)
void SetDebug (integer $state)
integer setErrorHandling (integer $val)
boolean setPConnect (boolean $conntype)
integer set_CharSet (string $charset)
integer set_TimeNames (string $locale)
string Version ()
Variables
string $AdminEmail (line 102)
  • var: Email Address for the administrator of this project
string $appname (line 90)
  • var: Name of Application that uses this class
string $characterset (line 110)
  • var: Character set to use.
string $classversion (line 92)
  • var: Version of this class in format VER.REV
string $currentQuery (line 94)
  • var: Contains the actual query to be processed.
string $database (line 84)
  • var: Name of schema to be used
integer $debug (line 98)
  • var: Flag indicates debug mode of class
string $host (line 76)
  • var: Name of database to connect to
string $locale (line 112)
  • var: Locale to use for DATE_FORMAT(), DAYNAME() and MONTHNAME() SQL functions.
integer $myErrno (line 104)
  • var: Error code of last mysql operation (set in Print_Error())
string $myErrStr (line 106)
  • var: Error string of last mysql operation (set in Print_Error())
boolean $new_link (line 117)
  • var: TRUE => Always create NEW connections, FALSE => Do not create new connections (default)
  • since: 0.38
integer $num_rows (line 122)
  • var: Number of rows returned from a previous SELECT/SHOW statement.
  • since: 0.38
string $pass (line 82)
  • var: Password of database user used for connection
integer $port (line 78)
  • var: Portnumber to use when connecting to MySQL
integer $querycounter (line 86)
  • var: Counts the processed queries against the database
float $querytime (line 88)
  • var: Contains the total SQL execution time in microseconds.
string $SAPI_type (line 100)
  • var: The SAPI type of php (used to detect CLI sapi)
integer $showError (line 96)
  • var: Flag indicates how the class should interact with errors
mixed $sock (line 74)
  • var: Internal connection handle
boolean $usePConnect (line 108)
  • var: TRUE = Connect() uses Persistant connection, else new one (Default)
string $user (line 80)
  • var: Name of database user used for connection
Methods
Constructor db_MySQL (line 131)

Constructor of this class.

The constructor takes default values from dbdefs.inc.php. Please see this file for further informations about the setable options.

db_MySQL db_MySQL ([string $extconfig = ''])
  • string $extconfig: Optional other filename for dbdefs.inc.php, defaults to "dbdefs.inc.php".
AffectedRows (line 793)

Returns count of affected rows by last DML operation.

integer AffectedRows ([mixed $extsock = -1])
  • mixed $extsock: Optionally an external MySQL socket to use. If not given the internal socket is used.
checkSock (line 889)

Checks if we are already connected to our database.

If not terminates by calling Print_Error().

void checkSock ()
Commit (line 684)

Commits current transaction.

Note: Requires transactional tables, else does nothing!

void Commit ()
Connect (line 228)

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.

mixed Connect ([string $user = ''], [string $pass = ''], [string $host = ''], [string $db = ''], [integer $port = 0])
  • string $user: Username used to connect to DB
  • string $pass: Password to use for given username
  • string $host: Hostname of database to connect to
  • integer $port: TCP port to use for connection. Defaults to 3306.
  • string $db: Schema to use on MySQL DB Server
ConvertMySQLDate (line 819)

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.

string ConvertMySQLDate (string $mysqldate, string $fmtstring)
  • string $mysqldate: The MySQL default datestring in format YYYY-MM-DD HH:MI:SS
  • string $fmtstring: A strftime() compatible format string.
DescTable (line 1162)

Returns the description for a given table.

Array returned has the following fields:

  1. => name of the field
  2. => type of field
  3. => The fieldsize
  4. => Field flags (like auto_increment).

  • return: Numerical array with all required table informations.
  • since: 0.37
array DescTable (string $tname)
  • string $tname: Name of table to describe.
Disconnect (line 349)

Disconnects from MySQL.

You may optionally pass an external link identifier.

void Disconnect ([mixed $other_sock = -1])
  • mixed $other_sock: Optionally your own connection handle to close, else internal will be used
EscapeString (line 1058)

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.

  • return: The escaped string.
  • since: 0.35
string EscapeString (string $str)
  • string $str: The string to escape.
FetchResult (line 608)

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.

array FetchResult (mixed $result, [integer $resflag = MYSQL_ASSOC])
  • mixed $result: The resource identifier as returned by QueryResult()
  • 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
FreeResult (line 632)

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 memory.

mixed FreeResult (mixed $result)
  • mixed $result: The resource identifier you want to be freed.
GetClassVersion (line 763)

Returns version of this class.

  • return: The version of this class.
string GetClassVersion ()
GetConnectionHandle (line 867)

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: Internal socket value
  • since: 0.32
mixed GetConnectionHandle ()
GetDebug (line 725)

Returns the current debug setting.

integer GetDebug ()
GetErrno (line 971)

Retrieve last mysql error number.

  • return: The MySQL error number of the last operation.
  • see: mysql_errno()
  • since: 0.33
integer GetErrno ([mixed $other_sock = -1])
  • mixed $other_sock: Optionally your own connection handle to check, else internal will be used.
GetErrorText (line 1004)

Retrieve last mysql error description.

  • return: The MySQL error description of the last operation.
  • see: mysql_error()
  • since: 0.33
string GetErrorText ([mixed $other_sock = -1])
  • mixed $other_sock: Optionally your own connection handle to check, else internal will be used.
getmicrotime (line 837)

Returns microtime in format s.mmmmm.

Used to measure SQL execution time.

  • return: the current time in microseconds.
float getmicrotime ()
GetQueryCount (line 666)

Returns amount of queries executed by this class.

  • return: Querycount
integer GetQueryCount ()
GetQueryTime (line 675)

Returns amount of time spend on queries executed by this class.

  • return: Time in seconds.msecs spent in executin MySQL code.
float GetQueryTime ()
get_CharSet (line 1139)

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: The current settings for the character_set variables.
  • since: 0.36
array get_CharSet ()
get_TimeNames (line 1101)

Method to return the current MySQL setting for the lc_time_names variable.

  • return: The current setting for the lc_time_names variable.
  • since: 0.36
string get_TimeNames ()
IsQueryWithResult (line 534)

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.

  • return: Returns TRUE if query can return a result set, else returns FALSE for DML or other unknown commands (i.e. SET).
bool IsQueryWithResult (string $querystring)
  • string $querystring: The query to check.
LastInsertId (line 774)

Returns last used auto_increment id.

  • return: The last automatic insert id that was assigned by the MySQL server.
  • see: mysql_insert_id()
integer LastInsertId ([mixed $extsock = -1])
  • mixed $extsock: Optionally an external MySQL socket to use. If not given the internal socket is used.
NumRows (line 1298)

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.

integer NumRows ()
PerformNewInsert (line 1213)

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. Looks like this:

  • $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!

  • return: A numeric array with [0] => created query count, [1] => Querysize or FALSE in case of an error.
  • see: examples/new_insert.php
array PerformNewInsert (string $table_name, array &$fields, [string $sql = 'INSERT'])
  • string $table_name: Name of table to perform the insert against.
  • array &$fields: The associative array
  • string $sql: Either "INSERT" or "REPLACE", no other command is allowed here!
PrintDebug (line 735)

Handles output according to internal debug flag.

void PrintDebug (string $msg)
  • string $msg: The Text to be included in the debug message.
Print_Error (line 376)

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!

void Print_Error ([string $ustr = ""], [mixed $var2dump = ""])
  • string $ustr: User-defined Error string to show
  • mixed $var2dump: Optionally a variable to print out with print_r()
Query (line 482)

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.

mixed Query (string $querystring, [integer $resflag = MYSQL_ASSOC], [integer $no_exit = 0])
  • string $querystring: The query to be executed
  • 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
  • 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() and exists.
QueryResult (line 561)

Performs a multi-row query and returns result identifier.

  • return: A resource identifier or an errorcode (if $no_exit = 1)
  • see: mysql_query()
mixed QueryResult (string $querystring, [integer $no_exit = 0])
  • string $querystring: The Query to be executed
  • 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()
Rollback (line 697)

Rollback current transaction.

Note: Requires transactional tables, else does nothing!

void Rollback ()
SendMailOnError (line 906)

Send error email if programmer has defined a valid email address and enabled it with the define MYSQLDB_SENTMAILONERROR.

void SendMailOnError (integer $merrno, string $merrstr, string $uerrstr)
  • integer $merrno: MySQL errno number
  • string $merrstr: MySQL error description
  • string $uerrstr: User-supplied error description
SetConnectionHandle (line 878)

Allows to set internal socket to external value.

void SetConnectionHandle (mixed $extsock)
  • mixed $extsock: New socket handle to set (as returned from mysql_connect())
SetDebug (line 715)

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!

void SetDebug (integer $state)
  • integer $state: The DEBUG Level you want to be set
setErrorHandling (line 853)

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.

  • return: The previous value for error handling.
  • since: 0.28
integer setErrorHandling (integer $val)
  • integer $val: The Error Handling mode you wish to use.
setPConnect (line 1038)

Sets connection behavour.

If FALSE class uses mysql_connect to connect. If TRUE class uses mysql_pconnect to connect (Persistant connection).

  • return: The previous state.
  • since: 0.35
boolean setPConnect (boolean $conntype)
  • boolean $conntype: The new setting for persistant connections.
set_CharSet (line 1120)

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.

  • return: 1 If all works, else 0 in case of an error.
  • since: 0.36
integer set_CharSet (string $charset)
  • string $charset: The charset to set on the MySQL server side.
set_TimeNames (line 1084)

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!

  • return: 0 If an error occures or 1 if change was successful.
  • since: 0.36
integer set_TimeNames (string $locale)
  • string $locale: A locale string for the language you want to set, i.e. 'de_DE'.
Version (line 646)

Returns MySQL Server Version.

Opens an own connection if no active one exists.

  • return: MySQL Server Version
string Version ()

Documentation generated on Sat, 07 Aug 2010 10:18:23 +0200 by phpDocumentor 1.4.3