Ultimate MySQL Wrapper Class for PHP 8.1+
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.
Determines if an error throws an exception
Instance flag for auto-escaping values in BuildSQL* helpers
Forces buffered results for SELECT queries (true = Buffered, false = Unbuffered)
Enables automatic reconnection on connection loss
Constructor: Opens the connection to the database
Destructor: Closes the connection to the database
Sets auto-escape mode for this instance (used by BuildSQL* helpers)
Sets global auto-escape mode for all new instances
Sets unbuffered (streaming) mode for SELECT queries. Default is TRUE (Unbuffered).
Enables or disables automatic reconnection on connection loss
Enables or disables throwing exceptions on database errors
Sets the debug log file path (must be absolute and outside webroot recommended)
Automatically performs an INSERT or UPDATE based on record existence (uses Transaction + SELECT FOR UPDATE)
Checks if the internal result pointer is at the first row (index 0)
[STATIC] Builds a SQL DELETE statement with optional WHERE clause and auto-escape support
[STATIC] Builds a SQL INSERT statement with auto-escape support
[STATIC] Builds a SELECT SQL statement with full clause support (WHERE, COLUMNS, ORDER BY, LIMIT, OFFSET)
[STATIC] Builds a SQL UPDATE statement with auto-escape support
[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.
[STATIC] Escapes a database identifier (table/column name) with backticks. Validates against forbidden chars.
Closes the database connection and frees resources (statements, results)
Deletes rows matching the WHERE conditions (requires WHERE to prevent mass delete)
Checks if the internal result pointer is at or past the last row
Gets the last error description
Gets the last error number
[STATIC] Converts a value to boolean using loose semantics (Y, T, 1, ON, etc.)
Retrieves column comments for a table or the current result set
Gets the number of columns in a table or the current result set
Gets the generic data type (e.g., 'int', 'varchar') for a column
Gets the full MySQL column type definition (e.g., 'varchar(255)', 'int(11)')
Gets the zero-based index of a column by name
Gets the maximum length (display size) of a column
Gets the name of a column by its zero-based index
Gets an array of column names for a table or the current result set
Gets a list of all tables in the current database
Generates an HTML table representation of the current result set. Respects MYSQL_MAX_BUFFERED_ROWS safety limit.
Returns the current result set as a JSON string. Respects MYSQL_MAX_BUFFERED_ROWS safety limit.
Gets the last auto-generated INSERT ID
Gets the last executed SQL query string
Returns the current result set as an XML string. Respects MYSQL_MAX_BUFFERED_ROWS safety limit.
Checks if a query returns any rows (executes SQL if provided)
Inserts a single row into a table
Checks if the database connection is active
[STATIC] Determines if a value is a date PHP can convert. Use DateTime objects or ISO 8601 strings with SQLValue() instead.
Terminates script execution with an error message
Moves the internal result pointer to the first row (index 0). Not supported for unbuffered prepared statements without mysqlnd.
Moves the internal result pointer to the last row. Not supported for unbuffered prepared statements without mysqlnd.
Opens a database connection. Supports SSL options and connection timeout.
Prepares a SQL statement for execution with placeholders (?)
Binds a single parameter to the prepared statement. Must be called before Execute().
Binds multiple parameters at once. Types auto-detected if omitted.
Executes the prepared statement. Handles SELECT (buffered/unbuffered) and DML automatically.
Fetches the next row from a prepared statement (buffered or unbuffered fallback). Memory efficient for streaming.
Fetches all remaining rows from a prepared statement into an array. Respects MYSQL_MAX_BUFFERED_ROWS safety limit.
Closes the current prepared statement and resets state
Gets the row count for the last prepared SELECT statement. Requires mysqlnd (mysqli_stmt_get_result). Throws error if unavailable.
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.
Executes a query and returns all rows as an array. Shortcut for Query() + RecordsArray().
Executes a query and returns the first row as an object
Executes a query and returns the first row as an array
Executes a query and returns the first column of the first row
Executes a query and times the execution duration
Gets the internal mysqli_result or mysqli_stmt object
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.
Frees the memory associated with the last query result
Fetches the current/next row as an object (stdClass). Advances internal pointer. Seeks if row number provided.
Fetches the current/next row as an array. Advances internal pointer. Seeks if row number provided.
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.
Seeks the internal result pointer to a specific row number. Not supported for unbuffered prepared statements.
Gets the current zero-based row pointer position
Selects the default database for the connection
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.
Selects all rows from a table (SELECT * FROM table). Shortcut for SelectRows() with no filters.
[STATIC] Converts a boolean into a formatted TRUE or FALSE value of choice
Escapes a string for safe use in SQL queries (mysqli_real_escape_string). Requires active connection.
[STATIC] Formats a PHP value into a SQL literal string based on datatype. Handles NULL, strings, numbers, booleans, dates (DateTime/ISO8601), blobs.
Gets the duration of the last timed query
Starts the internal timer
Stops the internal timer and calculates duration
Begins a database transaction
Commits the current transaction
Rolls back the current transaction
Checks if currently inside a transaction
Gets the transaction nesting depth (emulated, always 0 or 1)
Truncates a table (removes all rows, resets auto_increment)
Updates rows matching WHERE conditions (requires WHERE to prevent mass update)
Advances to the next result set in a multi-query execution
SQL Value Type: Bit (1 or 0)
SQL Value Type: Boolean (1 or 0)
SQL Value Type: Date (YYYY-MM-DD)
SQL Value Type: Datetime (YYYY-MM-DD HH:MM:SS)
SQL Value Type: Integer, Int, BigInt, etc. (raw number)
SQL Value Type: Text, Varchar, Char, etc. (escaped string)
SQL Value Type: Time (HH:MM:SS)
SQL Value Type: Boolean ('T' or 'F')
SQL Value Type: Boolean ('Y' or 'N')
Documentation generated for Ultimate MySQL Wrapper Class v5.0