Ultimate MySQL Class

Documentation for version 5.0

Description

Ultimate MySQL Wrapper Class for PHP 8.1+

  • Establish MySQL server connections easily
  • Execute SQL queries (Buffered & Unbuffered/Streaming modes)
  • Prepared Statements support (with mysqlnd fallback)
  • 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
  • Memory safety guards for large result sets
  • SQL Anonymization for debug logs
  • And much more!

Changelog:
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, fixes
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 version 4.0 with PHPUnit test cases and bug fixes
Nov 06, 2022 - Version 4.1 - Library installable via Composer
Nov 08, 2022 - Version 4.2 - Added debug mode
Nov 10, 2022 - Version 4.3 - Composer version compatible with PHP 7
Nov 12, 2022 - Version 4.4 - Improved debug mode for composer version
Feb 14, 2023 - Version 4.5 - PHP 8.2 compatible
Jan 23, 2024 - Version 4.6 - Bug fixes + PHP 8.3 compatible
Aug 18, 2026 - Version 5.0 - PHP 8.1+ only
    - Requires PHP 8.1+ (readonly props, never return type, union types, mixed)
    - Fixed Prepared Statement OOM fallback (removed store_result)
    - Default Unbuffered Mode for memory safety
    - Added MYSQL_MAX_BUFFERED_ROWS safety limit (default 50k)
    - Added MYSQL_DEBUG_ANONIMIZATION constant
    - New SQLVALUE constants: BIT, YN, TF
    - New methods: Prepare, Execute, BindParam, BindParams, Fetch, FetchAll, CloseStatement, PreparedRowCount
    - New helpers: EscapeIdentifier, SetUnbufferedMode, SetAutoReconnect, AutoInsertUpdate
    - Updated BuildSQL* methods with auto-escape support
    - SelectRows now supports OFFSET and resultType
    - Query() supports buffered override parameter
    - Open() supports SSL and Connection Timeout
    - Deprecated: IsDate(), SQLUnfix()

 

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.

Memory Safety & Unbuffered Mode

Version 5.0 defaults to Unbuffered Mode (streaming) for SELECT queries to prevent memory exhaustion on large datasets. Methods like RecordsArray(), GetJSON(), GetHTML(), GetXML(), FetchAll() buffer the entire result set and are protected by the MYSQL_MAX_BUFFERED_ROWS constant (default 50,000 rows). Exceeding this limit throws a RuntimeException (if ThrowExceptions is true) or returns false and sets an error. Use RowArray() / Fetch() loops for streaming large results without limits.

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_TF = "t-f"
SQLVALUE_YN = "y-n"
Variable Summary
boolean $autoEscapeValues (Instance)
boolean $forceBufferedResults (Instance)
boolean $autoReconnect (Instance)
Method Summary
MySQL __construct ([boolean $connect = true], [string $database = ""], [string $server = "localhost"], [string $username = ""], [string $password = ""], [string $charset = "utf8mb4"], [boolean $persistent = false])
void __destruct ()
int|bool AutoInsertUpdate (string $tableName, array $valuesArray, array $whereArray)
boolean BeginningOfSeek ()
string BuildSQLDelete (string $tableName, array $whereArray, [boolean $autoEscape = false])
string BuildSQLInsert (string $tableName, array $valuesArray, [boolean $autoEscape = false])
string BuildSQLSelect (string $tableName, [array $whereArray = null], [array|string $columns = null], [array|string $sortColumns = null], [boolean $sortAscending = true], [int $limit = null], [int $offset = null], [boolean $autoEscape = false])
string BuildSQLUpdate (string $tableName, array $valuesArray, [array $whereArray = null], [boolean $autoEscape = false])
string BuildSQLWhereClause (array $whereArray, [boolean $autoEscape = false])
string EscapeIdentifier (string $identifier)
boolean Close ()
boolean DeleteRows (string $tableName, array $whereArray)
boolean EndOfSeek ()
string|bool Error ()
int|bool ErrorNumber ()
boolean GetBooleanValue (mixed $value)
array|bool GetColumnComments (string $table, [string $resultType = "ASSOC"])
int|bool GetColumnCount ([string $table = ""])
string|bool GetColumnDataType (string|int $column, [string $table = ""])
string|bool GetColumnDataTypeName (string|int $column, [string $table = ""])
int|bool GetColumnID (string $column, [string $table = ""])
int|bool GetColumnLength (string|int $column, [string $table = ""])
string|bool GetColumnName (int $columnID, [string $table = ""])
array|bool GetColumnNames ([string $table = ""])
array|bool GetTables ()
string|bool GetHTML ([boolean $showCount = true], [string $styleTable = null], [string $styleHeader = null], [string $styleData = null])
string GetJSON ()
int|string|bool GetLastInsertID ()
string GetLastSQL ()
string GetXML ()
boolean HasRecords ([string $sql = ""])
int|bool InsertRow (string $tableName, array $valuesArray)
boolean IsConnected ()
boolean IsDate (mixed $value) [Deprecated]
never Kill ([string $message = ''])
boolean MoveFirst ()
boolean MoveLast ()
boolean Open ([string $database = null], [string $server = null], [string $username = null], [string $password = null], [string $charset = null], [boolean $persistent = false], [int $connectTimeout = 0], [array $sslOptions = null])
boolean Prepare (string $sql)
boolean BindParam (mixed $value, string $type = 's')
boolean BindParams (array $params, string $types = '')
boolean Execute ()
array|bool Fetch ([int $resultType = MYSQLI_BOTH])
array|bool FetchAll ([int $resultType = MYSQLI_BOTH])
boolean CloseStatement ()
int|bool PreparedRowCount ()
mysqli_result|bool Query (string $sql, [bool $buffered = null])
array|bool QueryArray (string $sql, [int $resultType = MYSQLI_BOTH])
object|bool QuerySingleRow (string $sql)
array|bool QuerySingleRowArray (string $sql, [int $resultType = MYSQLI_BOTH])
mixed QuerySingleValue (string $sql)
mysqli_result|bool QueryTimed (string $sql)
mysqli_result|mysqli_stmt|bool|null Records ()
array|bool RecordsArray ([int $resultType = MYSQLI_BOTH])
boolean Release ()
object|bool Row ([int $optional_row_number = null])
array|bool RowArray ([int $optional_row_number = null], [int $resultType = MYSQLI_BOTH])
int|string|bool RowCount ()
boolean Seek (int $row_number)
int 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], [int $limit = null], [int $offset = null], [int $resultType = MYSQLI_BOTH])
boolean SelectTable (string $tableName)
string SQLBooleanValue (mixed $value, mixed $trueValue, mixed $falseValue, [string $datatype = self::SQLVALUE_TEXT])
string|bool SQLFix (string $value)
string SQLValue (mixed $value, [string $datatype = self::SQLVALUE_TEXT])
string TimerDuration ([int $decimals = 4])
void TimerStart ()
void TimerStop ()
boolean TransactionBegin ()
boolean TransactionEnd ()
boolean TransactionRollback ()
boolean IsInTransaction ()
boolean TruncateTable (string $tableName)
boolean UpdateRows (string $tableName, array $valuesArray, array $whereArray)
void SetAutoEscapeValues (boolean $flag)
void SetGlobalAutoEscapeValues (boolean $flag)
void SetUnbufferedMode (boolean $flag)
void SetAutoReconnect (boolean $flag)
void SetThrowExceptions (boolean $flag)
void SetDebugPath (string $path)
boolean NextResult ()
Variables
boolean $ThrowExceptions = false (line 47)

Determines if an error throws an exception

  • var: Set to true to throw error exceptions (RuntimeException)
  • access: protected
boolean $autoEscapeValues = false

Instance flag for auto-escaping values in BuildSQL* helpers

  • var: Controlled via SetAutoEscapeValues() / SetGlobalAutoEscapeValues()
  • access: private
boolean $forceBufferedResults = false (Default: Unbuffered/Streaming)

Forces buffered results for SELECT queries (true = Buffered, false = Unbuffered)

  • var: Controlled via SetUnbufferedMode()
  • access: private
boolean $autoReconnect = false

Enables automatic reconnection on connection loss

  • var: Controlled via SetAutoReconnect()
  • access: private
Methods
Constructor __construct

Constructor: Opens the connection to the database

  • access: public
MySQL __construct ([boolean $connect = true], [string $database = ""], [string $server = "localhost"], [string $username = ""], [string $password = ""], [string $charset = "utf8mb4"], [boolean $persistent = false])
  • boolean $connect: Auto-connect when object is created
  • string $database: Database name
  • string $server: Host address
  • string $username: User name
  • string $password: Password
  • string $charset: Character set (default utf8mb4)
  • boolean $persistent: Use persistent connection
Destructor __destruct

Destructor: Closes the connection to the database

  • access: public
void __destruct ()
SetAutoEscapeValues

Sets auto-escape mode for this instance (used by BuildSQL* helpers)

  • access: public
void SetAutoEscapeValues (boolean $flag)
  • boolean $flag: True to enable auto-escaping
SetGlobalAutoEscapeValues

Sets global auto-escape mode for all new instances

  • access: public
  • static
void SetGlobalAutoEscapeValues (boolean $flag)
  • boolean $flag: True to enable auto-escaping globally
SetUnbufferedMode

Sets unbuffered (streaming) mode for SELECT queries. Default is TRUE (Unbuffered).

  • access: public
void SetUnbufferedMode (boolean $flag)
  • boolean $flag: True for UNBUFFERED (streaming), False for BUFFERED
SetAutoReconnect

Enables or disables automatic reconnection on connection loss

  • access: public
void SetAutoReconnect (boolean $flag)
  • boolean $flag: True to enable auto-reconnect
SetThrowExceptions

Enables or disables throwing exceptions on database errors

  • access: public
void SetThrowExceptions (boolean $flag)
  • boolean $flag: True to throw RuntimeException on errors
SetDebugPath

Sets the debug log file path (must be absolute and outside webroot recommended)

  • access: public
void SetDebugPath (string $path)
  • string $path: Absolute path to the debug log file
AutoInsertUpdate

Automatically performs an INSERT or UPDATE based on record existence (uses Transaction + SELECT FOR UPDATE)

  • return: Returns INSERT ID on new record, TRUE on update, FALSE on error
  • access: public
int|bool AutoInsertUpdate (string $tableName, array $valuesArray, array $whereArray)
  • string $tableName: The table name
  • array $valuesArray: Associative array of column=>value data to insert/update
  • array $whereArray: Associative array for WHERE clause (required)
BeginningOfSeek

Checks if the internal result pointer is at the first row (index 0)

  • return: True if at beginning, false otherwise
  • access: public
boolean BeginningOfSeek ()
BuildSQLDelete

[STATIC] Builds a SQL DELETE statement with optional WHERE clause and auto-escape support

  • return: The DELETE SQL statement
  • access: public
  • static
string BuildSQLDelete (string $tableName, array $whereArray, [boolean $autoEscape = false])
  • string $tableName: Table name
  • array $whereArray: WHERE conditions (optional)
  • boolean $autoEscape: Auto-escape values via SQLValue()
BuildSQLInsert

[STATIC] Builds a SQL INSERT statement with auto-escape support

  • return: The INSERT SQL statement
  • access: public
  • static
string BuildSQLInsert (string $tableName, array $valuesArray, [boolean $autoEscape = false])
  • string $tableName: Table name
  • array $valuesArray: Associative array of column=>value
  • boolean $autoEscape: Auto-escape values via SQLValue()
BuildSQLSelect

[STATIC] Builds a SELECT SQL statement with full clause support (WHERE, COLUMNS, ORDER BY, LIMIT, OFFSET)

  • return: The SELECT SQL statement
  • access: public
  • static
string BuildSQLSelect (string $tableName, [array $whereArray = null], [array|string $columns = null], [array|string $sortColumns = null], [boolean $sortAscending = true], [int $limit = null], [int $offset = null], [boolean $autoEscape = false])
  • string $tableName: Table name
  • array $whereArray: WHERE conditions (supports operators, IN, NULL, _raw)
  • array|string $columns: Columns to select (null = *)
  • array|string $sortColumns: ORDER BY columns
  • boolean $sortAscending: Sort direction (true=ASC)
  • int $limit: LIMIT count
  • int $offset: OFFSET count
  • boolean $autoEscape: Auto-escape values in WHERE
BuildSQLUpdate

[STATIC] Builds a SQL UPDATE statement with auto-escape support

  • return: The UPDATE SQL statement
  • access: public
  • static
string BuildSQLUpdate (string $tableName, array $valuesArray, [array $whereArray = null], [boolean $autoEscape = false])
  • string $tableName: Table name
  • array $valuesArray: Column=>value pairs to set
  • array $whereArray: WHERE conditions (optional)
  • boolean $autoEscape: Auto-escape values
BuildSQLWhereClause

[STATIC] Builds a WHERE clause from an array. Supports operators in keys (e.g. "age >"), IN/NOT IN arrays, NULL checks, and '_raw' key for raw SQL fragments.

  • return: The WHERE clause (prefixed with " WHERE " or " AND ")
  • access: public
  • static
string BuildSQLWhereClause (array $whereArray, [boolean $autoEscape = false])
  • array $whereArray: Conditions array
  • boolean $autoEscape: Auto-escape values
EscapeIdentifier

[STATIC] Escapes a database identifier (table/column name) with backticks. Validates against forbidden chars.

  • return: Escaped identifier (e.g., `table`)
  • access: public
  • static
string EscapeIdentifier (string $identifier)
  • string $identifier: The identifier to escape
Close

Closes the database connection and frees resources (statements, results)

  • return: True on success, false on failure
  • access: public
boolean Close ()
DeleteRows

Deletes rows matching the WHERE conditions (requires WHERE to prevent mass delete)

  • return: True on success, false on error
  • access: public
boolean DeleteRows (string $tableName, array $whereArray)
  • string $tableName: Table name
  • array $whereArray: WHERE conditions (required)
EndOfSeek

Checks if the internal result pointer is at or past the last row

  • return: True if at end (or empty), false otherwise
  • access: public
boolean EndOfSeek ()
Error

Gets the last error description

  • return: Error string with code (e.g., "Error (#1064)"), or false if no error
  • access: public
string|bool Error ()
ErrorNumber

Gets the last error number

  • return: MySQL error code, or false if no error
  • access: public
int|bool ErrorNumber ()
GetBooleanValue

[STATIC] Converts a value to boolean using loose semantics (Y, T, 1, ON, etc.)

  • return: True if value represents truthy state
  • access: public
  • static
boolean GetBooleanValue (mixed $value)
  • mixed $value: Value to check
GetColumnComments

Retrieves column comments for a table or the current result set

  • return: Array of comments, or false on error
  • access: public
array|bool GetColumnComments (string $table, [string $resultType = "ASSOC"])
  • string $table: Table name (empty = current result set)
  • string $resultType: Return format: ASSOC, NUM, BOTH
GetColumnCount

Gets the number of columns in a table or the current result set

  • return: Column count, or false on error
  • access: public
int|bool GetColumnCount ([string $table = ""])
  • string $table: Table name (empty = current result set)
GetColumnDataType

Gets the generic data type (e.g., 'int', 'varchar') for a column

  • return: Type name string, or false on error
  • access: public
string|bool GetColumnDataType (string|int $column, [string $table = ""])
  • string|int $column: Column name or index
  • string $table: Table name (empty = current result set)
GetColumnDataTypeName

Gets the full MySQL column type definition (e.g., 'varchar(255)', 'int(11)')

  • return: Type definition string, or false on error
  • access: public
string|bool GetColumnDataTypeName (string|int $column, [string $table = ""])
  • string|int $column: Column name or index
  • string $table: Table name
GetColumnID

Gets the zero-based index of a column by name

  • return: Column index, or false if not found
  • access: public
int|bool GetColumnID (string $column, [string $table = ""])
  • string $column: Column name
  • string $table: Table name (empty = current result set)
GetColumnLength

Gets the maximum length (display size) of a column

  • return: Column length, or false on error
  • access: public
int|bool GetColumnLength (string|int $column, [string $table = ""])
  • string|int $column: Column name or index
  • string $table: Table name (empty = current result set)
GetColumnName

Gets the name of a column by its zero-based index

  • return: Column name, or false on error
  • access: public
string|bool GetColumnName (int $columnID, [string $table = ""])
  • int $columnID: Column index
  • string $table: Table name (empty = current result set)
GetColumnNames

Gets an array of column names for a table or the current result set

  • return: Array of column names, or false on error
  • access: public
array|bool GetColumnNames ([string $table = ""])
  • string $table: Table name (empty = current result set)
GetTables

Gets a list of all tables in the current database

  • return: Array of table names, or false on error
  • access: public
array|bool GetTables ()
GetHTML

Generates an HTML table representation of the current result set. Respects MYSQL_MAX_BUFFERED_ROWS safety limit.

  • return: HTML string, or false if no result set / error / safety limit exceeded
  • access: public
string|bool GetHTML ([boolean $showCount = true], [string $styleTable = null], [string $styleHeader = null], [string $styleData = null])
  • boolean $showCount: Prepend row count
  • string $styleTable: Inline CSS for <table>
  • string $styleHeader: Inline CSS for header <td>
  • string $styleData: Inline CSS for data <td>
GetJSON

Returns the current result set as a JSON string. Respects MYSQL_MAX_BUFFERED_ROWS safety limit.

  • return: JSON encoded string (pretty print), or 'null' if no result / error / safety limit exceeded
  • access: public
string GetJSON ()
GetLastInsertID

Gets the last auto-generated INSERT ID

  • return: The ID (int|string), or false if none
  • access: public
int|string|bool GetLastInsertID ()
GetLastSQL

Gets the last executed SQL query string

  • return: The SQL query
  • access: public
string GetLastSQL ()
GetXML

Returns the current result set as an XML string. Respects MYSQL_MAX_BUFFERED_ROWS safety limit.

  • return: XML document string
  • access: public
string GetXML ()
HasRecords

Checks if a query returns any rows (executes SQL if provided)

  • return: True if rows exist, false otherwise
  • access: public
boolean HasRecords ([string $sql = ""])
  • string $sql: Optional SQL to execute first
InsertRow

Inserts a single row into a table

  • return: Insert ID on success, false on error
  • access: public
int|bool InsertRow (string $tableName, array $valuesArray)
  • string $tableName: Table name
  • array $valuesArray: Associative array of column=>value
IsConnected

Checks if the database connection is active

  • return: True if connected
  • access: public
boolean IsConnected ()
IsDate [Deprecated]

[STATIC] Determines if a value is a date PHP can convert. Use DateTime objects or ISO 8601 strings with SQLValue() instead.

  • return: True if value is date
  • access: public
  • static
  • deprecated: Since v5.0
boolean IsDate (mixed $value)
  • mixed $value: Value to check
Kill

Terminates script execution with an error message

  • return: Never returns
  • access: public
never Kill ([string $message = ''])
  • string $message: Optional custom message (defaults to last error)
MoveFirst

Moves the internal result pointer to the first row (index 0). Not supported for unbuffered prepared statements without mysqlnd.

  • return: True on success, false on failure or empty result
  • access: public
boolean MoveFirst ()
MoveLast

Moves the internal result pointer to the last row. Not supported for unbuffered prepared statements without mysqlnd.

  • return: True on success, false on failure or empty result
  • access: public
boolean MoveLast ()
Open

Opens a database connection. Supports SSL options and connection timeout.

  • return: True on success, false on failure
  • access: public
boolean Open ([string $database = null], [string $server = null], [string $username = null], [string $password = null], [string $charset = null], [boolean $persistent = false], [int $connectTimeout = 0], [array $sslOptions = null])
  • string $database: Database name (overrides constructor)
  • string $server: Host (overrides constructor)
  • string $username: User (overrides constructor)
  • string $password: Pass (overrides constructor)
  • string $charset: Charset (overrides constructor)
  • boolean $persistent: Use persistent connection
  • int $connectTimeout: Connection timeout in seconds
  • array $sslOptions: SSL options array (keys: key, cert, ca, capath, cipher)
Prepare

Prepares a SQL statement for execution with placeholders (?)

  • return: True on success, false on failure
  • access: public
boolean Prepare (string $sql)
  • string $sql: The SQL query with placeholders (?)
BindParam

Binds a single parameter to the prepared statement. Must be called before Execute().

  • return: True on success, false on error
  • access: public
boolean BindParam (mixed $value, string $type = 's')
  • mixed $value: The value to bind (by reference)
  • string $type: Type specifier: 'i' (int), 'd' (double), 's' (string), 'b' (blob)
BindParams

Binds multiple parameters at once. Types auto-detected if omitted.

  • return: True on success, false on error
  • access: public
boolean BindParams (array $params, string $types = '')
  • array $params: Array of values
  • string $types: String of type specifiers (e.g., 'issd')
Execute

Executes the prepared statement. Handles SELECT (buffered/unbuffered) and DML automatically.

  • return: True on success, false on failure
  • access: public
boolean Execute ()
Fetch

Fetches the next row from a prepared statement (buffered or unbuffered fallback). Memory efficient for streaming.

  • return: Row array, or false if no more rows / error
  • access: public
array|bool Fetch ([int $resultType = MYSQLI_BOTH])
  • int $resultType: Fetch mode (MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH)
FetchAll

Fetches all remaining rows from a prepared statement into an array. Respects MYSQL_MAX_BUFFERED_ROWS safety limit.

  • return: Array of rows, or false if safety limit exceeded / error
  • access: public
array|bool FetchAll ([int $resultType = MYSQLI_BOTH])
  • int $resultType: Fetch mode
CloseStatement

Closes the current prepared statement and resets state

  • return: True if a statement was closed, false if none active
  • access: public
boolean CloseStatement ()
PreparedRowCount

Gets the row count for the last prepared SELECT statement. Requires mysqlnd (mysqli_stmt_get_result). Throws error if unavailable.

  • return: Row count, or false if unsupported/error
  • access: public
int|bool PreparedRowCount ()
Query

Executes a raw SQL query directly. Detects SELECT vs DML to handle buffering and insert IDs. Blocks multi-statement queries for security. Supports buffered override.

  • return: mysqli_result on success (SELECT), true on success (DML), false on error
  • access: public
mysqli_result|bool Query (string $sql, [bool $buffered = null])
  • string $sql: The SQL query
  • bool $buffered: Override default buffering (true=buffered, false=unbuffered, null=use class default)
QueryArray

Executes a query and returns all rows as an array. Shortcut for Query() + RecordsArray().

  • return: Array of rows, or false on error
  • access: public
array|bool QueryArray (string $sql, [int $resultType = MYSQLI_BOTH])
  • string $sql: The SQL query
  • int $resultType: Fetch mode
QuerySingleRow

Executes a query and returns the first row as an object

  • return: Row object, or false if no rows / error
  • access: public
object|bool QuerySingleRow (string $sql)
  • string $sql: The SQL query
QuerySingleRowArray

Executes a query and returns the first row as an array

  • return: Row array, or false if no rows / error
  • access: public
array|bool QuerySingleRowArray (string $sql, [int $resultType = MYSQLI_BOTH])
  • string $sql: The SQL query
  • int $resultType: Fetch mode
QuerySingleValue

Executes a query and returns the first column of the first row

  • return: The value, or false if no rows / error
  • access: public
mixed QuerySingleValue (string $sql)
  • string $sql: The SQL query
QueryTimed

Executes a query and times the execution duration

  • return: mysqli_result or false
  • access: public
mysqli_result|bool QueryTimed (string $sql)
  • string $sql: The SQL query
Records

Gets the internal mysqli_result or mysqli_stmt object

  • return: The result resource
  • access: public
mysqli_result|mysqli_stmt|bool|null Records ()
RecordsArray

Fetches all rows from the last query result into an array. Buffers entire result set in memory. Respects MYSQL_MAX_BUFFERED_ROWS. Not supported for unbuffered prepared statements.

  • return: Array of rows, or false on error / safety limit
  • access: public
array|bool RecordsArray ([int $resultType = MYSQLI_BOTH])
  • int $resultType: Fetch mode
Release

Frees the memory associated with the last query result

  • return: True on success
  • access: public
boolean Release ()
Row

Fetches the current/next row as an object (stdClass). Advances internal pointer. Seeks if row number provided.

  • return: Row object, or false if no row / error
  • access: public
object|bool Row ([int $optional_row_number = null])
  • int $optional_row_number: Zero-based row index to seek to (optional)
RowArray

Fetches the current/next row as an array. Advances internal pointer. Seeks if row number provided.

  • return: Row array, or false if no row / error
  • access: public
array|bool RowArray ([int $optional_row_number = null], [int $resultType = MYSQLI_BOTH])
  • int $optional_row_number: Zero-based row index to seek to (optional)
  • int $resultType: Fetch mode (MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH)
RowCount

Gets the number of rows in the last result set (SELECT) or affected rows (DML). For unbuffered prepared statements without mysqlnd, returns false with error.

  • return: Row count, affected rows, or false on error/unsupported
  • access: public
int|string|bool RowCount ()
Seek

Seeks the internal result pointer to a specific row number. Not supported for unbuffered prepared statements.

  • return: True on success, false on failure / out of bounds
  • access: public
boolean Seek (int $row_number)
  • int $row_number: Zero-based row index
SeekPosition

Gets the current zero-based row pointer position

  • return: Current position (-1 if before first, count if after last)
  • access: public
int SeekPosition ()
SelectDatabase

Selects the default database for the connection

  • return: True on success, false on failure
  • access: public
boolean SelectDatabase (string $database, [string $charset = ""])
  • string $database: Database name
  • string $charset: Charset to set (optional)
SelectRows

Selects rows from a table with full query building capabilities (WHERE, COLUMNS, ORDER BY, LIMIT, OFFSET). Executes the query and stores result internally. Returns true on success, false on error. Use RowCount(), RecordsArray(), RowArray(), Fetch() etc. to access results.

  • return: True on success, false on error
  • access: public
boolean SelectRows (string $tableName, [array $whereArray = null], [array|string $columns = null], [array|string $sortColumns = null], [boolean $sortAscending = true], [int $limit = null], [int $offset = null], [int $resultType = MYSQLI_BOTH])
  • string $tableName: Table name
  • array $whereArray: WHERE conditions (supports '_raw', operators in keys, etc.)
  • array|string $columns: Columns to select (null = *)
  • array|string $sortColumns: Column(s) to sort by
  • boolean $sortAscending: Sort direction (true=ASC, false=DESC)
  • int $limit: LIMIT count
  • int $offset: OFFSET count
  • int $resultType: Fetch mode (MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH)
SelectTable

Selects all rows from a table (SELECT * FROM table). Shortcut for SelectRows() with no filters.

  • return: True on success, false on error
  • access: public
boolean SelectTable (string $tableName)
  • string $tableName: Table name
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 (mixed $value, mixed $trueValue, mixed $falseValue, [string $datatype = self::SQLVALUE_TEXT])
  • mixed $value: Value to analyze for TRUE or FALSE
  • mixed $trueValue: Value to use if TRUE
  • mixed $falseValue: Value to use if FALSE
  • string $datatype: Use SQLVALUE constants
SQLFix

Escapes a string for safe use in SQL queries (mysqli_real_escape_string). Requires active connection.

  • return: Escaped string, or false if no connection
  • access: public
string|bool SQLFix (string $value)
  • string $value: The string to escape
SQLValue

[STATIC] Formats a PHP value into a SQL literal string based on datatype. Handles NULL, strings, numbers, booleans, dates (DateTime/ISO8601), blobs.

  • return: SQL literal (e.g., 'hello', 123, NULL, '2023-01-01')
  • access: public
  • static
string SQLValue (mixed $value, [string $datatype = self::SQLVALUE_TEXT])
  • mixed $value: The value to format
  • string $datatype: One of SQLVALUE_* constants (text, number, date, datetime, time, boolean, y-n, t-f, bit)
TimerDuration

Gets the duration of the last timed query

  • return: Formatted duration in seconds
  • access: public
string TimerDuration ([int $decimals = 4])
  • int $decimals: Decimal places for formatting
TimerStart

Starts the internal timer

  • access: public
void TimerStart ()
TimerStop

Stops the internal timer and calculates duration

  • access: public
void TimerStop ()
TransactionBegin

Begins a database transaction

  • return: True on success, false on failure (e.g., already in transaction)
  • access: public
boolean TransactionBegin ()
TransactionEnd

Commits the current transaction

  • return: True on success, false on failure
  • access: public
boolean TransactionEnd ()
TransactionRollback

Rolls back the current transaction

  • return: True on success, false on failure
  • access: public
boolean TransactionRollback ()
IsInTransaction

Checks if currently inside a transaction

  • return: True if in transaction
  • access: public
boolean IsInTransaction ()
GetTransactionDepth

Gets the transaction nesting depth (emulated, always 0 or 1)

  • return: 1 if in transaction, 0 otherwise
  • access: public
int GetTransactionDepth ()
TruncateTable

Truncates a table (removes all rows, resets auto_increment)

  • return: True on success, false on error
  • access: public
boolean TruncateTable (string $tableName)
  • string $tableName: Table name
UpdateRows

Updates rows matching WHERE conditions (requires WHERE to prevent mass update)

  • return: True on success, false on error
  • access: public
boolean UpdateRows (string $tableName, array $valuesArray, array $whereArray)
  • string $tableName: Table name
  • array $valuesArray: Column=>value pairs to set
  • array $whereArray: WHERE conditions (required)
NextResult

Advances to the next result set in a multi-query execution

  • return: True if next result exists, false otherwise
  • access: public
boolean NextResult ()
Class Constants (Use with SQLValue() method)
SQLVALUE_BIT = "bit"

SQL Value Type: Bit (1 or 0)

SQLVALUE_BOOLEAN = "boolean"

SQL Value Type: Boolean (1 or 0)

SQLVALUE_DATE = "date"

SQL Value Type: Date (YYYY-MM-DD)

SQLVALUE_DATETIME = "datetime"

SQL Value Type: Datetime (YYYY-MM-DD HH:MM:SS)

SQLVALUE_NUMBER = "number"

SQL Value Type: Integer, Int, BigInt, etc. (raw number)

SQLVALUE_TEXT = "text"

SQL Value Type: Text, Varchar, Char, etc. (escaped string)

SQLVALUE_TIME = "time"

SQL Value Type: Time (HH:MM:SS)

SQLVALUE_TF = "t-f"

SQL Value Type: Boolean ('T' or 'F')

SQLVALUE_YN = "y-n"

SQL Value Type: Boolean ('Y' or 'N')

Documentation generated for Ultimate MySQL Wrapper Class v5.0