Ultimate MySQL Class

Documention for version 4.6

Description

Ultimate MySQL Wrapper Class for PHP 7 & PHP 8

  • Establish MySQL server connections easily
  • Execute SQL queries
  • Retrieve query results into objects or arrays
  • Retrieve the last inserted ID
  • Manage transactions (transaction processing)
  • Retrieve the list tables of a database
  • Retrieve the list fields of a table (or field comments)
  • Retrieve the length or data type of a field
  • Measure the time a query takes to execute
  • Display query results in an HTML table
  • Easy formatting for SQL parameters and values
  • Generate SQL Selects, Inserts, Updates, and Deletes
  • Error handling with error numbers and text
  • And much more!

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, fixe
Jul 16, 2007 - Bug fix, removed test, major improvements in error handling
Aug 11, 2007 - Added InsertRow() and UpdateRows() 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(), UpdateRows() 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
Aug 16, 2013 - Version 3.0 - Updated class to mysqli extension
Oct 26, 2022 - Created Github repository with the aim of making the class compatible with PHP 8
Nov 04, 2022 - Released the version 4.0 with the PHPUnit test cases and a lot of bug fix
Nov 06, 2022 - Version 4.1 - The library is now installable with Composer.
Nov 08, 2022 - Version 4.2 - Added the debug mode
Nov 10, 2022 - Version 4.3 - Composer version is now also compatible with PHP 7
Nov 12, 2022 - Version 4.4 - Improved the debug mode for the composer version
Feb 14, 2023 - Version 4.5 - PHP 8.2 compatible
Jan 23, 2024 - Version 4.6 - Bug fixes provided by Paul Pazderski + PHP 8.3 compatible

 

Usage (normal library)

include "mysql.class.php";

$db = new MySQL();
$db = new MySQL(true, "database");
$db = new MySQL(true, "database", "localhost", "username", "password");

 

Usage (composer)

require "vendor/autoload.php";

$db = new MySQL();
$db = new MySQL(true, "database");
$db = new MySQL(true, "database", "localhost", "username", "password");

 

Debug mode

The script looks for a file called .debugmysql (within the root directory or within the composer's vendor / module folder) and, if found, enters debug mode.
When debug mode is active, it writes all SQL queries executed inside the .debugmysql file.

Class Constant Summary (Use with SQLValue() method)
SQLVALUE_BIT = "bit"
SQLVALUE_BOOLEAN = "boolean"
SQLVALUE_DATE = "date"
SQLVALUE_DATETIME = "datetime"
SQLVALUE_NUMBER = "number"
SQLVALUE_TEXT = "text"
SQLVALUE_TIME = "time"
SQLVALUE_T_F = "t-f"
SQLVALUE_Y_N = "y-n"
Variable Summary
Method Summary
MySQL __construct ([boolean $connect = true], [string $database = ""], [string $server = ""], [string $username = ""], [string $password = ""], [string $charset = ""])
void __destruct ()
boolean AutoInsertUpdate (string $tableName, array $valuesArray, array $whereArray)
boolean BeginningOfSeek ()
string BuildSQLDelete (string $tableName, array $whereArray)
string BuildSQLInsert (string $tableName, array $valuesArray)
string BuildSQLSelect (string $tableName, [array $whereArray = null], [array/string $columns = null], [array/string $sortColumns = null], [boolean $sortAscending = true], [integer/string $limit = null])
string BuildSQLUpdate (string $tableName, array $valuesArray, [array $whereArray = null])
string BuildSQLWhereClause (array $whereArray)
object Returns Close ()
boolean DeleteRows (string $tableName, [array $whereArray = null])
boolean EndOfSeek ()
string Error ()
integer ErrorNumber ()
boolean GetBooleanValue (any $value)
array GetColumnComments (string $table)
integer GetColumnCount ([string $table = ""])
string GetColumnDataType (string $column, [string $table = ""])
string GetColumnDataTypeName (string $column, [string $table = ""])
integer GetColumnID (string $column, [string $table = ""])
integer GetColumnLength (string $column, [string $table = ""])
integer GetColumnName (string $columnID, [string $table = ""])
array GetColumnNames ([string $table = ""])
string GetHTML ([boolean $showCount = true], [string $styleTable = null], [string $styleHeader = null], [string $styleData = null])
string GetJSON ()
integer GetLastInsertID ()
string GetLastSQL ()
array GetTables ()
boolean GetXML ()
string HasRecords ([string $sql = ""])
integer InsertRow (string $tableName, array $valuesArray)
boolean IsConnected ()
boolean IsDate (date/string $value)
void Kill ([mixed $message = ''])
boolean MoveFirst ()
boolean MoveLast ()
boolean Open ([string $database = ""], [string $server = ""], [string $username = ""], [string $password = ""], [string $charset = ""], [boolean $pcon = false])
object PHP Query (string $sql)
array QueryArray (string $sql, [integer $resultType = MYSQL_BOTH])
object PHP QuerySingleRow (string $sql)
array QuerySingleRowArray (string $sql, [integer $resultType = MYSQL_BOTH])
mixed QuerySingleValue (string $sql)
object PHP QueryTimed (string $sql)
object PHP Records ()
Records RecordsArray ([integer $resultType = MYSQL_BOTH])
boolean Release ()
object PHP Row ([integer $optional_row_number = null])
array RowArray ([integer $optional_row_number = null], [integer $resultType = MYSQL_BOTH])
integer RowCount ()
object Fetched Seek (integer $row_number)
integer SeekPosition ()
boolean SelectDatabase (string $database, [string $charset = ""])
boolean SelectRows (string $tableName, [array $whereArray = null], [array/string $columns = null], [array/string $sortColumns = null], [boolean $sortAscending = true], [integer/string $limit = null])
boolean SelectTable (string $tableName)
string SQLBooleanValue (any $value, any $trueValue, any $falseValue, [string $datatype = self::SQLVALUE_TEXT])
string SQLFix (string $value)
string SQLUnfix (string $value)
string SQLValue (any $value, [string $datatype = self::SQLVALUE_TEXT])
Float TimerDuration ([integer $decimals = 4])
void TimerStart ()
void TimerStop ()
boolean TransactionBegin ()
boolean TransactionEnd ()
boolean TransactionRollback ()
boolean TruncateTable (string $tableName)
boolean UpdateRows (string $tableName, array $valuesArray, [array $whereArray = null])
Variables
boolean $ThrowExceptions = false (line 47)

Determines if an error throws an exception

  • var: Set to true to throw error exceptions
  • access: public
Methods
Constructor __construct

Constructor: Opens the connection to the database

  • access: public
MySQL __construct ([boolean $connect = true], [string $database = ""], [string $server = ""], [string $username = ""], [string $password = ""], [string $charset = ""])
  • boolean $connect: (Optional) Auto-connect when object is created
  • string $database: (Optional) Database name
  • string $server: (Optional) Host address
  • string $username: (Optional) User name
  • string $password: (Optional) Password
  • string $charset: (Optional) Character set (i.e. 'utf8')

Example:

$db = new MySQL();
$db = new MySQL(true, "database");
$db = new MySQL(true, "database", "localhost", "username", "password");

Destructor __destruct

Destructor: Closes the connection to the database

  • access: public
void __destruct ()
AutoInsertUpdate (line 113)

Automatically does an INSERT or UPDATE depending if an existing record exists in a table

  • return: Returns TRUE on success or FALSE on error
boolean AutoInsertUpdate (string $tableName, array $valuesArray, array $whereArray)
  • string $tableName: The name of the table
  • 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, ect)
  • array $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, ect).
BeginningOfSeek

Returns true if the internal pointer is at the beginning of the records

  • return: TRUE if at the first row or FALSE if not
  • access: public
boolean BeginningOfSeek ()

Example:

if ($db->BeginningOfSeek()) {
    echo "We are at the beggining of the record set";
}

BuildSQLDelete

[STATIC] Builds a SQL DELETE statement

  • return: Returns the SQL DELETE statement
  • access: public
  • static
string BuildSQLDelete (string $tableName, [array $whereArray = null])
  • string $tableName: The name of the table
  • array $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, ect). If not specified then all values in the table are deleted.
// 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);
BuildSQLInsert

[STATIC] Builds a SQL INSERT statement

  • return: Returns a SQL INSERT statement
  • access: public
  • static
string BuildSQLInsert (string $tableName, array $valuesArray)
  • string $tableName: The name of the table
  • 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, ect)
// 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);
BuildSQLSelect

Builds a simple SQL SELECT statement

  • return: Returns a SQL SELECT statement
  • access: public
  • static
string BuildSQLSelect (string $tableName, [array $whereArray = null], [array/string $columns = null], [array/string $sortColumns = null], [boolean $sortAscending = true], [integer/string $limit = null])
  • string $tableName: The name of the table
  • array $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, ect)
  • array/string $columns: (Optional) The column or list of columns to select
  • array/string $sortColumns: (Optional) Column or list of columns to sort by
  • boolean $sortAscending: (Optional) TRUE for ascending; FALSE for descending This only works if $sortColumns are specified
  • integer/string $limit: (Optional) The limit of rows to return
// 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);
BuildSQLUpdate

[STATIC] Builds a SQL UPDATE statement

  • return: Returns a SQL UPDATE statement
  • access: public
  • static
string BuildSQLUpdate (string $tableName, array $valuesArray, [array $whereArray = null])
  • string $tableName: The name of the table
  • 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, ect)
  • array $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, ect). If not specified then all values in the table are updated.
// 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)";
BuildSQLWhereClause

[STATIC] 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.

  • return: Returns a string containing the SQL WHERE clause
  • access: public
  • static
string BuildSQLWhereClause (array $whereArray)
  • array $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, ect)
Close

Close current MySQL connection

  • return: TRUE on success or FALSE on error
  • access: public
object Returns Close ()

Example:

$db->Close();

DeleteRows

Deletes rows in a table based on a WHERE filter (can be just one or many rows based on the filter)

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean DeleteRows (string $tableName, [array $whereArray = null])
  • string $tableName: The name of the table
  • array $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, ect). If not specified then all values in the table are deleted.

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();

}

EndOfSeek

Returns true if the internal pointer is at the end of the records

  • return: TRUE if at the last row or FALSE if not
  • access: public
boolean EndOfSeek ()

Example:

if ($db->EndOfSeek()) {
    
echo "We are at the end of the record set";
}

Error

Returns the last MySQL error as text

  • return: Error text from last known error or FALSE if no errors happened
  • access: public
string Error ()

Example:

if (! $db->Query("SELECT * FROM Table")) {
    echo $db->Error(); //Shows the error
}

if ($db->Error()) $db->Kill();

ErrorNumber

Returns the last MySQL error as a number

  • return: Error number from last known error or FALSE if no errors happened
  • access: public
integer ErrorNumber ()

Example:

if ($db->ErrorNumber() <> 0) {
    $db->Kill(); //show the error message
}

GetBooleanValue

[STATIC] Converts any value of any datatype into boolean (true or false)

  • return: Returns TRUE or FALSE
  • access: public
  • static
boolean GetBooleanValue (any $value)
  • any $value: Value to analyze for 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");

GetColumnComments

Returns the comments for fields in a table into an array or returns FALSE on error

  • return: An array that contains the column comments
  • access: public
array GetColumnComments (string $table, [string $resultType = ""])
  • string $table: Table name
  • string $resultType: (Optional) The type of array result. Can be: NUM, ASSOC, BOTH

Example:

$columns = $db->GetColumnComments("MyTable");
foreach ($columns as $column => $comment) {
    echo $column . " = " . $comment . "<br />\n";
}

GetColumnCount

This function returns the number of columns or returns FALSE on error

  • return: The total count of columns
  • access: public
integer GetColumnCount ([string $table = ""])
  • string $table: (Optional) If a table name is not specified, the column count is returned from the last query

Example:

echo "Total Columns: " . $db->GetColumnCount("MyTable");

GetColumnDataType

This function returns the data type ID for a specified column. If the column does not exists or no records exist, it returns FALSE

  • return: MySQL data (field) type
  • access: public
string GetColumnDataType (string $column, [string $table = ""])
  • string $column: Column name or number (first column is 0)
  • string $table: (Optional) If a table name is not specified, the last returned records are used

Example:

echo "Type: " . $db->GetColumnDataType("FirstName", "Customer");

GetColumnDataTypeName (Available from version 4.7)

This function returns the data type name for a specified column. If the column does not exists or no records exist, it returns FALSE

  • return: MySQL data (field) type
  • access: public
string GetColumnDataTypeName (string $column, [string $table = ""])
  • string $column: Column name or number (first column is 0)
  • string $table: (Optional) If a table name is not specified, the last returned records are used

Example:

echo "Type: " . $db->GetColumnDataTypeName("FirstName", "Customer");

GetColumnID

This function returns the position of a column

  • return: Column ID
  • access: public
integer GetColumnID (string $column, [string $table = ""])
  • string $column: Column name
  • string $table: (Optional) If a table name is not specified, the last returned records are used.

Example:

echo "Column Position: " . $db->GetColumnID("FirstName", "Customer");

GetColumnLength

This function returns the field length or returns FALSE on error

  • return: Field length
  • access: public
integer GetColumnLength (string $column, [string $table = ""])
  • string $column: Column name
  • string $table: (Optional) If a table name is not specified, the last returned records are used.

Example:

echo "Length: " . $db->GetColumnLength("FirstName", "Customer");

GetColumnName

This function returns the name for a specified column number. If the index does not exists or no records exist, it returns FALSE

  • return: Field Length
  • access: public
integer GetColumnName (string $columnID, [string $table = ""])
  • string $columnID: Column position (0 is the first column)
  • string $table: (Optional) If a table name is not specified, the last returned records are used.

Example:

echo "Column Name: " . $db->GetColumnName(0);

GetColumnNames

Returns the field names in a table in an array or NULL if the table has no fields

  • return: An array that contains the column names
  • access: public
array GetColumnNames ([string $table = ""])
  • string $table: (Optional) If a table name is not specified, the last returned records are used

Example:

$columns = $db->GetColumnNames("MyTable");
foreach ($columns as $columnName) {
    echo $columnName . "<br />\n";
}

GetHTML

This function returns the last query as an HTML table

  • return: HTML containing a table with all records listed
  • access: public
string GetHTML ([boolean $showCount = true], [string $styleTable = null], [string $styleHeader = null], [string $styleData = null])
  • boolean $showCount: (Optional) TRUE if you want to show the row count, FALSE if you do not want to show the count
  • string $styleTable: (Optional) Style information for the table
  • string $styleHeader: (Optional) Style information for the header row
  • string $styleData: (Optional) Style information for the cells

Example:

$db->Query("SELECT * FROM Customer");
echo $db->GetHTML();

GetJSON

Returns the last query as a JSON document

  • return: JSON document
  • access: public
string GetJSON ()
GetLastInsertID

Returns the last autonumber ID field from a previous INSERT query

  • return: ID number from previous INSERT query
  • access: public
integer GetLastInsertID ()

Example:

$sql = "INSERT INTO Employee (Name) Values ('Bob')";
if (! $db->Query($sql)) {
    $db->Kill();
}
echo "Last ID inserted was: " . $db->GetLastInsertID();

GetLastSQL

Returns the last SQL statement executed

  • return: Current SQL query string
  • access: public
string GetLastSQL ()

Example:

$sql = "INSERT INTO Employee (Name) Values ('Bob')";
if (! $db->Query($sql)) {$db->Kill();}
echo $db->GetLastSQL();

GetTables

This function returns table names from the database into an array. If the database does not contains any tables, the returned value is FALSE

  • return: An array that contains the table names
array GetTables ()

Example:

$tables = $db->GetTables();
foreach ($tables as $table) {
    echo $table . "<br />\n";
}

GetXML

Returns the last query as an XML Document.

  • return: A string that contains XML
string GetXML ()
HasRecords (line 801)

Determines if a query contains any rows

  • return: TRUE if records exist, FALSE if not or query error
  • access: public
boolean HasRecords ([string $sql = ""])
  • string $sql: [Optional] If specified, the query is first executed Otherwise, the last query is used for comparison
InsertRow

Inserts a row into a table in the connected database

  • return: Returns last insert ID on success or FALSE on failure
  • access: public
integer InsertRow (string $tableName, array $valuesArray)
  • string $tableName: The name of the table
  • 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, ect)

Example

// $arrayVariable["column name"] = formatted SQL value
$values["Name"] = MySQL::SQLValue("Violet");
$values["Age" = MySQL::SQLValue(777, MySQL::SQLVALUE_NUMBER);

// Execute the insert
$result = $db->InsertRow("MyTable", $values);

// If we have an error
if (! $result) {

    // Show the error and kill the script
    $db->Kill();

}
else {

    // No error, show the new record's ID
    echo "The new record's ID is: " . $result;

}

IsDate

[STATIC] Determines if a value of any data type is a date PHP can convert

  • return: Returns TRUE if value is date or FALSE if not date
  • access: public
  • static
boolean IsDate (date/string $value)
  • date/string $value

Example

if (MySQL::IsDate("January 1, 2000")) {
    echo "valid date";
}

Kill

Stop executing (die/exit) and show the last MySQL error message

  • access: public
void Kill ([mixed $message = ''])

Example:

//Stop executing the script and show the last error
$db->Kill();

MoveFirst

Seeks to the beginning of the records

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean MoveFirst ()

Example:

$db->MoveFirst();
while (! $db->EndOfSeek()) {
    $row = $db->Row();
    echo $row->ColumnName1 . " " . $row->ColumnName2 . "\n";
}

MoveLast

Seeks to the end of the records

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean MoveLast ()

Example:

$db->MoveLast();

Open

Connect to specified MySQL server

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean Open ([string $database = ""], [string $server = ""], [string $username = ""], [string $password = ""], [string $charset = ""], [boolean $pcon = false])
  • string $database: (Optional) Database name
  • string $server: (Optional) Host address
  • string $username: (Optional) User name
  • string $password: (Optional) Password
  • string $charset: (Optional) Character set
  • boolean $pcon: (Optional) Persistant connection

Example

if (! $db->Open("MyDatabase", "localhost", "user", "password")) {
    $db->Kill();
}

Query

Executes the given SQL query and returns the records

  • return: 'mysql result' resource object containing the records on SELECT, SHOW, DESCRIBE or EXPLAIN queries and returns; TRUE or FALSE for all others i.e. UPDATE, DELETE, DROP AND FALSE on all errors (setting the local Error message)
  • access: public
object PHP Query (string $sql)
  • string $sql: The query string should not end with a semicolon

Example:

if (! $db->Query("SELECT * FROM Table")) echo $db->Kill();

QueryArray (line 1017)

Executes the given SQL query and returns a multi-dimensional array

  • return: A multi-dimensional array containing all the data returned from the query or FALSE on all errors
  • access: public
array QueryArray (string $sql, [integer $resultType = MYSQL_BOTH])
  • string $sql: The query string should not end with a semicolon
  • integer $resultType: (Optional) The type of array Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
QuerySingleRow (line 1033)

Executes the given SQL query and returns only one (the first) row

  • return: resource object containing the first row or FALSE if no row is returned from the query
  • access: public
object PHP QuerySingleRow (string $sql)
  • string $sql: The query string should not end with a semicolon
QuerySingleRowArray (line 1051)

Executes the given SQL query and returns the first row as an array

  • return: An array containing the first row or FALSE if no row is returned from the query
  • access: public
array QuerySingleRowArray (string $sql, [integer $resultType = MYSQL_BOTH])
  • string $sql: The query string should not end with a semicolon
  • integer $resultType: (Optional) The type of array Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
QuerySingleValue (line 1067)

Executes a query and returns a single value. If more than one row is returned, only the first value in the first column is returned.

  • return: The value returned or FALSE if no value
  • access: public
mixed QuerySingleValue (string $sql)
  • string $sql: The query string should not end with a semicolon
QueryTimed

Executes the given SQL query, measures it, and saves the total duration in microseconds

  • return: 'mysql result' resource object containing the records on SELECT, SHOW, DESCRIBE or EXPLAIN queries and returns TRUE or FALSE for all others i.e. UPDATE, DELETE, DROP
  • access: public
object PHP QueryTimed (string $sql)
  • string $sql: The query string should not end with a semicolon

Example

$db->QueryTimed("SELECT * FROM MyTable");
echo "Query took " . $db->TimerDuration() . " microseconds";

Records

Returns the records from the last query

  • return: 'mysql result' resource object containing the records on SELECT, SHOW, DESCRIBE or EXPLAIN queries and returns TRUE or FALSE for all others i.e. UPDATE, DELETE, DROP
  • access: public
object PHP Records ()

Example:

$records = $db->Records();

RecordsArray

Returns all records from last query and returns contents as array or FALSE on error

  • return: in array form
  • access: public
Records RecordsArray ([integer $resultType = MYSQL_BOTH])
  • integer $resultType: (Optional) The type of array Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH

Example

$myArray = $db->RecordsArray(MYSQL_ASSOC);

Release

Frees memory used by the query results and returns the function result

  • return: Returns TRUE on success or FALSE on failure
  • access: public
boolean Release ()

Example:

$db->Release();

Row

Reads the current row and returns contents as a PHP object or returns false on error

  • return: object or FALSE on error
  • access: public
object PHP Row ([integer $optional_row_number = null])
  • integer $optional_row_number: (Optional) Use to specify a row

Example:

$db->MoveFirst();
while (! $db->EndOfSeek()) {
    $row = $db->Row();
    echo $row->ColumnName1 . " " . $row->ColumnName2 . "\n";
}

RowArray

Reads the current row and returns contents as an array or returns false on error

  • return: Array that corresponds to fetched row or FALSE if no rows
  • access: public
array RowArray ([integer $optional_row_number = null], [integer $resultType = MYSQL_BOTH])
  • integer $optional_row_number: (Optional) Use to specify a row
  • integer $resultType: (Optional) The type of array Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH

Example:

for ($index = 0; $index < $db->RowCount(); $index++) {
    $val = $db->RowArray($index);
}

RowCount

Returns the last query row count

  • return: Row count or FALSE on error
  • access: public
integer RowCount ()

Example:

$db->Query("SELECT * FROM Customer");
echo "Row Count: " . $db->RowCount();

Seek

Sets the internal database pointer to the specified row number and returns the result

  • return: row as PHP object
  • access: public
object Fetched Seek (integer $row_number)
  • integer $row_number: Row number

Example:

$db->Seek(0); //Move to the first record

SeekPosition

Returns the current cursor row location

  • return: Current row number
  • access: public
integer SeekPosition ()

Example:

echo "Current Row Cursor : " . $db->GetSeekPosition();

SelectDatabase

Selects a different database and character set

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean SelectDatabase (string $database, [string $charset = ""])
  • string $database: Database name
  • string $charset: (Optional) Character set (i.e. 'utf8')

Example:

$db->SelectDatabase("DatabaseName");

SelectRows

Gets rows in a table based on a WHERE filter

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean SelectRows (string $tableName, [array $whereArray = null], [array/string $columns = null], [array/string $sortColumns = null], [boolean $sortAscending = true], [integer/string $limit = null])
  • string $tableName: The name of the table
  • array $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, ect)
  • array/string $columns: (Optional) The column or list of columns to select
  • array/string $sortColumns: (Optional) Column or list of columns to sort by
  • boolean $sortAscending: (Optional) TRUE for ascending; FALSE for descending This only works if $sortColumns are specified
  • integer/string $limit: (Optional) The limit of rows to return

Example

// $arrayVariable["column name"] = formatted SQL value
$filter["Color"] = MySQL::SQLValue("Violet");
$filter["Age"]   = MySQL::SQLValue(777, MySQL::SQLVALUE_NUMBER);

// Execute the select
$result = $db->SelectRows("MyTable", $filter);

// If we have an error
if (! $result) {

    // Show the error and kill the script
    $db->Kill();

}

SelectTable (line 1229)

Retrieves all rows in a specified table

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean SelectTable (string $tableName)
  • string $tableName: The name of the table
SQLBooleanValue

[STATIC] Converts a boolean into a formatted TRUE or FALSE value of choice

  • return: SQL formatted value of the specified data type
  • access: public
  • static
string SQLBooleanValue (any $value, any $trueValue, any $falseValue, [string $datatype = 'string'])
  • any $value: value to analyze for TRUE or FALSE
  • any $trueValue: value to use if TRUE
  • any $falseValue: value to use if FALSE
  • string $datatype: Use SQLVALUE constants or the strings: string, text, varchar, char, boolean, bool, Y-N, T-F, bit, date, datetime, time, integer, int, number, double, float

Example:

echo MySQL::SQLBooleanValue(false, "1", "0", MySQL::SQLVALUE_NUMBER);
echo MySQL::SQLBooleanValue($test, "Jan 1, 2007 ", "2007/06/01", MySQL::SQLVALUE_DATE);
echo MySQL::SQLBooleanValue("ON", "Ya", "Nope");
echo MySQL::SQLBooleanValue(1, '+', '-');

SQLFix

[STATIC] Returns string suitable for SQL
Deprecated - instead use SQLValue($value, "text")

  • return: SQL formatted value
  • access: public
  • static
string SQLFix (string $value)
  • string $value

Example:

$value = MySQL::SQLFix("\hello\ /world/");
echo $value . "\n" . MySQL::SQLUnfix($value);

SQLUnfix

[STATIC] Returns MySQL string as normal string
Removed from version 3.0

  • access: public
  • static
string SQLUnfix (string $value)
  • string $value

Example:

$value = MySQL::SQLFix("\hello\ /world/");
echo $value . "\n" . MySQL::SQLUnfix($value);

SQLValue

[STATIC] Formats any value into a string suitable for SQL statements (NOTE: Also supports data types returned from the gettype function)

  • access: public
  • static
string SQLValue (any $value, [string $datatype = SQLVALUE_TEXT])
  • any $value: Any value of any type to be formatted to SQL
  • string $datatype: Use SQLVALUE constants or the strings: string, text, varchar, char, boolean, bool, Y-N, T-F, bit, date, datetime, time, integer, int, number, double, float

Example:

echo MySQL::SQLValue("it's a string", "text");
$sql = "SELECT * FROM Table WHERE Field1 = " . MySQL::SQLValue("123", MySQL::SQLVALUE_NUMBER);
$sql = "UPDATE Table SET Field1 = " . MySQL::SQLValue("July 4, 2007", MySQL::SQLVALUE_DATE);

TimerDuration

Returns last measured duration (time between TimerStart and TimerStop)

  • return: Microseconds elapsed
  • access: public
Float TimerDuration ([integer $decimals = 4])
  • integer $decimals: (Optional) The number of decimal places to show

Example:

$db->TimerStart();
// Do something or run some queries
$db->TimerStop();
echo $db->TimerDuration(2) . " microseconds";

TimerStart

Starts time measurement (in microseconds)

  • access: public
void TimerStart ()

Example:

$db->TimerStart();
// Do something or run some queries
$db->TimerStop();
echo $db->TimerDuration() . " microseconds";

TimerStop

Stops time measurement (in microseconds)

  • access: public
void TimerStop ()

Example:

$db->TimerStart();
// Do something or run some queries
$db->TimerStop();
echo $db->TimerDuration() . " microseconds";

TransactionBegin

Starts a transaction

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean TransactionBegin ()

Example:

$sql = "INSERT INTO MyTable (Field1, Field2) Values ('abc', 123)";
$db->TransactionBegin();
if ($db->Query($sql)) {
    $db->TransactionEnd();
    echo "Last ID inserted was: " . $db->GetLastInsertID();
}
else {
    $db->TransactionRollback();
    echo "Query Failed";
}

TransactionEnd

Ends a transaction and commits the queries

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean TransactionEnd ()

Example:

$sql = "INSERT INTO MyTable (Field1, Field2) Values ('abc', 123)";
$db->TransactionBegin();
if ($db->Query($sql)) {
    $db->TransactionEnd();
    echo "Last ID inserted was: " . $db->GetLastInsertID();
}
else {
    $db->TransactionRollback();
    echo "Query Failed";
}

TransactionRollback

Rolls the transaction back

  • return: Returns TRUE on success or FALSE on failure
  • access: public
boolean TransactionRollback ()

Example:

$sql = "INSERT INTO MyTable (Field1, Field2) Values ('abc', 123)";
$db->TransactionBegin();
if ($db->Query($sql)) {
    $db->TransactionEnd();
    echo "Last ID inserted was: " . $db->GetLastInsertID();
}
else {
    $db->TransactionRollback();
    echo "Query Failed";
}

TruncateTable (line 1503)

Truncates a table removing all data

  • return: Returns TRUE on success or FALSE on error
boolean TruncateTable (string $tableName)
  • string $tableName: The name of the table
UpdateRows

Updates a row in a table from the connected database

  • return: Returns TRUE on success or FALSE on error
  • access: public
boolean UpdateRows (string $tableName, array $valuesArray, [array $whereArray = null])
  • string $tableName: The name of the table
  • 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, ect)
  • array $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, ect). If not specified then all values in the table are updated.

// Create an array that holds the update information
// $arrayVariable["column name"] = formatted SQL value
$update["Name"] = MySQL::SQLValue("Bob");
$update["Age" = MySQL::SQLValue(25, MySQL::SQLVALUE_NUMBER);

// Execute the update where the ID is 1
if (! $db->UpdateRows("test", $values, array("id" => 1))) $db->Kill

Class Constants (Use with SQLValue() method)
SQLVALUE_BIT = "bit"
SQLVALUE_BOOLEAN = "boolean"
SQLVALUE_DATE = "date"
SQLVALUE_DATETIME = "datetime"
SQLVALUE_NUMBER = "number"
SQLVALUE_TEXT = "text"
SQLVALUE_TIME = "time"
SQLVALUE_T_F = "t-f"
SQLVALUE_Y_N = "y-n"

Documentation generated by phpDocumentor 1.3.0RC3 and modified by Jeff L. Williams