Luminova Framework

PHP Luminova: MySQLi Database Driver

Last updated: 2026-11-28 20:57:12

Luminova’s MySQLi driver for MySQL connections, query execution, transactions, and native MySQLi access.

The MysqliDriver class is Luminova's MySQLi based database driver. It implements DatabaseDriverInterface and exposes the same API as the PDO driver, so most application code works with either one. It also allows you to use named placeholders (:name) even though MySQLi only supports positional ones.

You normally don't create it yourself. The Connection class builds it when the connection setting is mysqli.

Getting Started

Get the driver from a connection instance:

use Luminova\Database\Connection;

$db = Connection::getInstance()->database();

Or create a standalone driver from a configuration object:

use App\Config\Database;
use Luminova\Database\Connection;

$db = Connection::with(Database::fromArray([
    'connection' => 'mysqli',
    'host'       => 'localhost',
    'port'       => 3306,
    'database'   => 'my_db',
    'username'   => 'root',
    'password'   => 'password',
]));

Configuration keys used by this driver:

KeyDefaultDescription
hostlocalhostDatabase server host. Prefixed with p: for persistent connections.
port3306Database server port.
database''Database name.
usernamerootDatabase username.
password''Database password.
charsetutf8mb4Connection charset, applied with set_charset(). utf8 and utf-8 are converted to utf8mb4. Skipped when commands contains a SET NAMES statement.
emulate_preparestrueControls how named placeholders are bound. See bind.
persistentfalseOpens a persistent connection. Always enabled when running in the CLI.
socketfalseConnect through a Unix socket.
socket_path''Unix socket path.
timeout0Connection timeout in seconds, applied when greater than zero.
commands[]List of SET statements to run after connecting.

Additional Notes

  • Error reporting:Creating the driver calls mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT), so MySQLi errors are thrown as exceptions instead of warnings. This setting is global to the PHP process. Connection errors are wrapped in a DatabaseException by connect().

  • Unix socket:A socket connection is used when running in the CLI, when socket is true, or when running inside the novakit container. The driver reads socket_path, then falls back to mysqli.default_socket from php.ini. A DatabaseException is thrown when neither is set.

  • Native types:The connection is opened with MYSQLI_OPT_INT_AND_FLOAT_NATIVE, so integer and float columns come back as PHP integers and floats.

  • Init commands:Only SET statements are allowed in commands, any other statement throws a DatabaseException.

  • Result fetching:Rows are read with mysqli_stmt::get_result(), which requires the mysqlnd driver.

  • Missing connection:Methods that need a live connection throw a DatabaseException when called before connect() or after close().


Basic Usage

Select rows with a prepared statement:

use Luminova\Database\Connection;

$db = Connection::getInstance()->database();

$db->prepare('SELECT * FROM users WHERE status = :status')
    ->bind(':status', 'active')
    ->execute();

$users = $db->fetchAll();

A named placeholder can be reused in the same query when emulate_prepares is true:

$db->prepare('SELECT * FROM users WHERE id = :id OR parent_id = :id')
    ->bind(':id', 10)
    ->execute();

$rows = $db->fetchAll();

Insert a row and read its ID:

$db->prepare('INSERT INTO users (name, email) VALUES (:name, :email)')
    ->execute([':name' => 'John Doe', ':email' => '[email protected]']);

$id = $db->getLastInsertId();

Run a transaction:

use Throwable;

try {
    $db->beginTransaction();

    $db->prepare('UPDATE accounts SET balance = balance - :amount WHERE id = :id')
        ->execute([':amount' => 100, ':id' => 1]);

    $db->prepare('UPDATE accounts SET balance = balance + :amount WHERE id = :id')
        ->execute([':amount' => 100, ':id' => 2]);

    $db->commit();
} catch (Throwable $e) {
    $db->rollback();
    throw $e;
}

Class Definition


Constants

Inherited from AbstractDatabaseDriver and accessed through the driver class, for example MysqliDriver::TRANSACTION_READ_ONLY.

ConstantValueUsed with
TRANSACTION_MODE_NONE0Skips changing the transaction mode.
TRANSACTION_WITH_CONSISTENT_SNAPSHOT1beginTransaction() flag.
TRANSACTION_READ_WRITE2beginTransaction() flag.
TRANSACTION_READ_UNCOMMITTED3setTransactionIsolation() level.
TRANSACTION_READ_ONLY4beginTransaction() flag.
TRANSACTION_READ_COMMITTED5setTransactionIsolation() level.
TRANSACTION_REPEATABLE_READ6setTransactionIsolation() level.
TRANSACTION_SERIALIZABLE7setTransactionIsolation() level.

Only TRANSACTION_WITH_CONSISTENT_SNAPSHOT, TRANSACTION_READ_WRITE and TRANSACTION_READ_ONLY are bit flags. Don't pass isolation level constants to beginTransaction(), their values overlap with the flag bits.


Methods

__construct

Creates the driver from a configuration object and switches MySQLi to exception reporting. It does not connect, call connect() to open the connection.

public function __construct(AbstractConfig $config)

Parameters:

ParameterTypeDescription
$configAbstractConfigThe core database connection configuration.

getInstance

Returns a shared driver instance, creating it with $config on the first call. The $config argument is ignored on later calls.

public static function getInstance(AbstractConfig $config) : DatabaseDriverInterface

Parameters:

ParameterTypeDescription
$configAbstractConfigThe configuration object used to initialize the database instance on first creation.

The shared instance is stored on AbstractDatabaseDriver, so PdoDriver and MysqliDriver share one slot. Whichever driver is created first is returned by later calls on either class.


connect

Opens the MySQLi connection. If the connection already exists, it returns true without reconnecting.

public function connect(): bool

Return:

bool - Return true when connected.

Throws:

  • Luminova\Exceptions\DatabaseException - If MySQLi cannot be initialized, a socket path is required but missing, an init command or the charset is invalid, or the connection fails. Other errors are wrapped in a DatabaseException.

isConnected

Checks the driver's connection state. It does not ping the server.

public function isConnected(): bool

Return:

bool - Returns true if connected, false otherwise.


close

Frees the active statement or result, closes the MySQLi connection, and decrements the open connection count.

public function close(): void

getDriver

Gets the driver name.

public function getDriver(): ?string

Return:

string|null - Return mysqli when connected, otherwise null.


getVersion

Gets the MySQL server version from mysqli::$server_info.

public function getVersion(): ?string

Return:

string|null - Return the version string, or null when not connected.


getConfig

Gets one configuration value, or all values when $property is null. Property names are trimmed and case insensitive.

public function getConfig(?string $property): mixed

Parameters:

ParameterTypeDescription
$property?stringConfiguration property name, case-insensitive. Pass null to retrieve all configuration settings.

Return:

mixed - Return the value, null for an empty or unknown key, or the full configuration array when $property is null.


getConn

Gets the driver connection wrapper, which gives access to the native mysqli object.

public function getConn(): DriverConnectionInterface

Return:

DriverConnectionInterface - Returns the driver connection wrapper.


getOpenConnections

Gets the number of open driver connections. The counter is static, so it is shared by all driver instances.

public static function getOpenConnections(): int

Return:

int - Returns the number of open connection.


enableNamedPlaceholder

Enables or disables named SQL placeholder support.

PDO supports named placeholders natively. MySQLi requires named placeholders to be converted to positional placeholders (?) before execution.

public function enableNamedPlaceholder(bool $enabled = true): static

Parameters:

ParameterTypeDescription
$enabledboolWhether to enable named placeholder support (default: true)..

Return:

static - Returns the instance of database driver interface.

Examples:

When named placeholders are enabled:

$driver->enableNamedPlaceholder();

$driver->prepare(
    'SELECT * FROM users WHERE id = :id AND age = :age'
);

$driver->bind(':id', 100);
$driver->bind(':age', 30);

When named placeholders are disabled:

$driver->enableNamedPlaceholder(false);

$driver->prepare(
    'SELECT * FROM users WHERE id = ? AND age = ?'
);

// Bind parameters in query order.
$driver->bind('?', 100); // id
$driver->bind('?', 30);  // age

// Or pass values in query order.
$driver->execute([100, 30]);

// Associative arrays are also supported and values are bound by query position.
$driver->execute(['id' => 100, 'age' => 30]);

Note:

  • For MySQLi, bind(), param(), and value() must bind positional parameters in the order they appear in the query when named placeholders are disabled.
  • The execute() method binds array values according to their order in the array, matching the positional placeholders in the query.
  • Ensure the number and order of values match the query's placeholders. Incorrect ordering may cause errors or produce unintended results.

isNamedPlaceholderEnabled

Checks whether named SQL placeholder support is enabled.

Returns true for PDO drivers, regardless of the configured setting, or when named placeholder support is enabled for MySQLi.

public function isNamedPlaceholderEnabled(): bool

Return:

bool - Returns true if named placeholders are enabled or the driver uses PDO.

Example:

if ($driver->isNamedPlaceholderEnabled()) {
    // Named placeholders are enabled.
}

exists

Checks whether a table exists in the current database. It runs its own prepared statement, so it replaces the current statement.

public function exists(string $table): bool

Parameters:

ParameterTypeDescription
$tablestringThe table name to check.

Return:

bool - Returns true if the table exists, otherwise false.


prepare

Prepares an SQL statement and resets the previous query state. Named placeholders such as :id are converted to ?, except inside quoted strings and quoted identifiers. Queries that already use ? work too.

public function prepare(string $query): self

Parameters:

ParameterTypeDescription
$querystringThe SQL query string to prepare.

Return:

self - Returns the instance of database driver interface.

Throws:


bind

Stores a value for a placeholder. The value is sent when execute() runs.

public function bind(string $param, mixed $value, ?int $type = null): self

Parameters:

ParameterTypeDescription
$paramstringPlaceholder name, with or without the leading colon (:id or id).
$valuemixedThe value to bind.
$type?intA PARAM_* constant. null resolves the type from the value.

Return:

self - Return the driver instance.

Throws:

Type mapping for $type:

TypeMySQLi type
PARAM_INT, PARAM_BOOLi
PARAM_FLOATd
PARAM_LOBb
PARAM_STR, PARAM_NULL, anything elses

How placeholders are matched depends on emulate_prepares:

  • true (default): bindings are matched by name in the order the placeholders appear, so one name can be used more than once.
  • false: values are bound in the order they were added, so bind them in the order the placeholders appear and don't reuse a name.

Bindings are cleared after every execute(), successful or not. Bind the values again before executing the statement a second time.


value

Alias of bind().

public function value(string $param, mixed $value, ?int $type = null): self

Parameters:

ParameterTypeDescription
$paramstringThe placeholder named parameter (e.g., ':columnName').
$valuemixedThe value to bind.
$type?int(Optional) The data type for the value (default: null). - PARAM_*, PARAM_* - For MySQLi and PDO driver. - PDO::PARAM_* - For PDO driver only supports custom type. - NULL - Resolve by value internally.

Return:

self - Returns the instance of database driver interface.


param

Binds a variable by reference. The variable is read when execute() runs, so changes made before then are used.

public function param(string $param, mixed &$value, ?int $type = null): self

Parameters:

ParameterTypeDescription
$paramstringThe placeholder named parameter (e.g., ':columnName').
$valuemixedThe variable to bind by reference.
$type?int(Optional) The data type for the value (default: null). - PARAM_*, PARAM_* - For MySQLi and PDO driver. - PDO::PARAM_* - For PDO driver only supports custom type. - NULL - Resolve by value internally.

Return:

self - Returns the instance of database driver interface.


getType

Resolves the parameter type code for a value. The result comes from the framework's database helper (Util::getMySqliTypeFromValue()).

public static function getType(mixed $value): int

Parameters:

ParameterTypeDescription
$valuemixedThe value to evaluate.

Return:

int - Returns the driver parameter type code.


execute

Binds the stored values and executes the prepared statement.

public function execute(?array $params = null): bool

Parameters:

ParameterTypeDescription
$params?array<array-key,mixed>Extra values keyed by placeholder name, or in positional order for ? placeholders. They are merged with values added through bind() and param(). When the same key exists in both, the value from $params is used.

Return:

bool - Return true on success.

Throws:


query

Runs an SQL query immediately, without placeholders, and keeps the result for fetching.

public function query(string $query): self

Parameters:

ParameterTypeDescription
$querystringThe SQL query string to execute.

Return:

self - Returns the instance of database driver interface.


exec

Runs an SQL statement without placeholders and returns the affected row count.

public function exec(string $query): int

Parameters:

ParameterTypeDescription
$querystringThe SQL query string to execute.

Return:

int - Return 0 when the statement fails, otherwise the affected rows with a minimum of 1. DDL statements that report no row count return 1.


ok

Checks whether the last query was executed successfully.

public function ok(): bool

Return:

bool - Returns true on success, false on failure.


getResult

Retrieves a result in the shape given by $returnMode.

public function getResult(int $returnMode = RETURN_ALL, int $fetchAS = FETCH_OBJ): mixed

Parameters:

ParameterTypeDescription
$returnModeintThe mode of the result to return (e.g., RETURN_*). Available Modes: - RETURN_NEXT: Fetch the next row (same as $db->fetchNext(...)). - RETURN_2D_NUM: Fetch a 2D numeric array (same as $db->getInt()). - RETURN_INT: Fetch a single integer value (same as $db->getCount()). - RETURN_ID: Fetch the last insert ID (same as $db->getLastInsertId()). - RETURN_COUNT: Fetch the count of affected rows (same as $db->rowCount()). - RETURN_COLUMN: Fetch specific columns (same as $db->getColumns()). - RETURN_ALL: Fetch all rows (same as $db->fetchAll(...)). - RETURN_STMT: Return the statement object itself (same as $db->getStatement()). - RETURN_RESULT: Return the query result in MySQLi or statement in PDO. (default RETURN_ALL).
$fetchASintThe result fetch mode (e.g, FETCH_*). Used only with RETURN_NEXT and RETURN_ALL modes.

Return:

mixed - Returns the result based on the specified mode and return type.

Return modeSame as
RETURN_NEXTfetchNext($fetchAS)
RETURN_ALLfetchAll($fetchAS)
RETURN_2D_NUMgetInt()
RETURN_INTgetCount()
RETURN_IDgetLastInsertId()
RETURN_COUNTrowCount()
RETURN_COLUMNgetColumns()
RETURN_STMTgetStatement()
RETURN_RESULTThe mysqli_result, or false when there is none.
Any other valuefetch($returnMode, $fetchAS)

$fetchAS is only used with RETURN_NEXT, RETURN_ALL, and the fallback to fetch().


fetch

Fetches rows from the active result.

public function fetch(int $returnMode = RETURN_ALL, int $fetchAS = FETCH_OBJ): mixed

Parameters:

ParameterTypeDescription
$returnModeintRETURN_ALL fetches all rows. RETURN_NEXT and RETURN_STREAM fetch one row per call (default RETURN_ALL).
$fetchASintOne of FETCH_ASSOC, FETCH_BOTH, FETCH_OBJ, FETCH_COLUMN, FETCH_KEY_PAIR, FETCH_NUM, FETCH_CLASS.

Return:

mixed - Return an array of rows for RETURN_ALL (empty when there are none), a single row, or false when the statement has no result set or no rows are left.

Throws:

How each mode is returned:

ModeAll rowsSingle row
FETCH_ASSOCAssociative arrays.Associative array.
FETCH_BOTHArrays with numeric and named keys.Associative array.
FETCH_NUMNumeric arrays.Numeric array.
FETCH_OBJ, FETCH_CLASSstdClass objects.stdClass object.
FETCH_COLUMNValues of the first column.Associative array.
FETCH_KEY_PAIRFirst column as key, second as value.Associative array.

After a fetch, the active object becomes the mysqli_result, so getStatement() returns null. For FETCH_CLASS rows are stdClass. To hydrate your own class, use fetchObject() or fetchAllObject().


fetchNext

Fetches the next row.

public function fetchNext(int $mode = FETCH_OBJ): array|object|bool

Parameters:

ParameterTypeDescription
$modeintThe result fetch mode (e.g, FETCH_* default: FETCH_OBJ).

Return:

array<array-key,mixed>|object|bool - Return the row, or false when no more rows are available.


getNext

Alias of fetchNext().

public function getNext(int $mode = FETCH_OBJ): array|object|bool

Parameters:

ParameterTypeDescription
$modeintThe result fetch mode (e.g, FETCH_* default: FETCH_OBJ).

Return:

array<array-key,mixed>|object|bool - Returns the next row as an object or array, or false if no more rows are available.


fetchAll

Fetches all remaining rows.

public function fetchAll(int $mode = FETCH_OBJ): array|object|bool

Parameters:

ParameterTypeDescription
$modeintThe result fetch mode (e.g, FETCH_* default: FETCH_OBJ).

Return:

array<array-key,mixed>|object|bool - Return the rows, or false when the result is empty.


getAll

Alias of fetchAll().

public function getAll(int $mode = FETCH_OBJ): array|object|bool

Parameters:

ParameterTypeDescription
$modeintThe result fetch mode (e.g, FETCH_* default: FETCH_OBJ).

Return:

array<array-key,mixed>|object|bool - Returns an array of result objects or arrays, an empty array if no rows are found or false.


fetchObject

Fetches the next row as an instance of a class. Without $class, a stdClass is returned.

public function fetchObject(?string $class = null, mixed ...$arguments): ?object

Parameters:

ParameterTypeDescription
$class?stringClass to instantiate. Defaults to stdClass.
$argumentsmixedConstructor arguments passed when creating the class instance.

Return:

object|null - Return the instance, or null when there is no row.

Example:

$db->prepare('SELECT * FROM users WHERE id = :id');
$db->execute([':id' => 1]);

$user = $db->fetchObject(App\Models\User::class);

fetchAllObject

Fetches all remaining rows as instances of a class. Without $class, stdClass objects are returned.

public function fetchAllObject(?string $class = null, mixed ...$arguments): array

Parameters:

ParameterTypeDescription
$class?stringFully qualified class name to instantiate. Defaults to stdClass. (default null).
$argumentsmixedConstructor arguments passed when creating class instances.

Return:

array<array-key,mixed> - Return a list of instances.


getColumns

Fetches all rows using a column oriented fetch mode.

public function getColumns(int $mode = FETCH_COLUMN): array

Parameters:

ParameterTypeDescription
$modeintThe fetch mode (default: FETCH_COLUMN).

Return:

array<array-key,mixed> - Return the values of the first column by default, or an empty array.


getInt

Fetches all rows as numeric arrays.

public function getInt(): array

Return:

array<array-key,mixed> - Returns a 2D array of integers, or an empty array if no results are found.


getCount

Reads the first value of the first row as an integer, which suits queries like SELECT COUNT(*).

public function getCount(): int

Return:

int - Return the value, or 0 when there are no results.


getLastInsertId

Gets the ID generated by the last INSERT from mysqli::$insert_id. MySQLi has no sequences, so $name is ignored.

public function getLastInsertId(?string $name = null): mixed

Parameters:

ParameterTypeDescription
$name?stringOptional sequence name. Ignored by drivers that do not support named sequences.

Return:

mixed - Return the ID, or null when not connected.


rowCount

Gets the row count recorded for the last successful query() or execute().

public function rowCount(): int

Return:

int - Returns the number of affected rows.

After a successful query() or execute() the value is never lower than 1, even when no rows matched. It is reset to 0 by prepare(), query() and exec() before they run.


columnCount

Gets the number of columns in the active statement or result.

public function columnCount(): int

Return:

int - Returns the number of result columns.


getStatement

Gets the active mysqli_stmt.

public function getStatement(): ?mysqli_stmt

Return:

mysqli_stmt|null - Return the statement, or null when there is none or a result has already been fetched.


isStatement

Checks whether there is an active mysqli_stmt.

public function isStatement(): bool

Return:

bool - Returns true if is a prepared statement, false otherwise.


isResult

Checks whether the active object is a mysqli_result.

public function isResult(): bool

Return:

bool - Returns true if query result, false otherwise.


free

Frees the active result, or the stored result of the active statement.

public function free(): void

beginTransaction

Starts a transaction, optionally with flags and a savepoint name.

public function beginTransaction(int $flags = self::TRANSACTION_MODE_NONE, ?string $name = null): bool

Parameters:

ParameterTypeDescription
$flagsintPassed to mysqli::begin_transaction(). Combine TRANSACTION_WITH_CONSISTENT_SNAPSHOT, TRANSACTION_READ_WRITE and TRANSACTION_READ_ONLY with \&#124; (default self::TRANSACTION_MODE_NONE).
$name?stringCreates a savepoint with this name after the transaction starts. Required when a transaction is already active.

Return:

bool - Return true when the transaction (and savepoint) started.

Throws:

Example:

$db->beginTransaction(
    MysqliDriver::TRANSACTION_WITH_CONSISTENT_SNAPSHOT | MysqliDriver::TRANSACTION_READ_ONLY
);

tryBeginTransaction

Same as beginTransaction(), but returns false instead of throwing.

public function tryBeginTransaction(
    int $flags = self::TRANSACTION_MODE_NONE,
    ?string $name = null
): bool

Parameters:

ParameterTypeDescription
$flagsintTransaction flags. Defaults to self::TRANSACTION_MODE_NONE. (default self::TRANSACTION_MODE_NONE).
$name?stringOptional savepoint name when supported. (default null).

Return:

bool - Returns true on success, or false if the transaction cannot start.


beginNestedTransaction

Starts a transaction when none is active, otherwise creates a savepoint with a generated name.

public function beginNestedTransaction(
    int $flags = self::TRANSACTION_MODE_NONE,
    bool $closeCursor = false
): string|bool|null

Parameters:

ParameterTypeDescription
$flagsintTransaction flags, used only when a new transaction starts (default self::TRANSACTION_MODE_NONE).
$closeCursorboolFree the active statement before starting (default false).

Return:

string|bool|null - Return null when a new transaction started, the savepoint name for a nested transaction, or false on failure.

Example:

$name = $db->beginNestedTransaction();

if ($name === false) {
    return;
}

try {
    // Run queries...

    if ($name !== null) {
        $db->release($name);
    } else {
        $db->commit();
    }
} catch (Throwable $e) {
    $db->rollback();
    throw $e;
}

tryBeginNestedTransaction

Same as beginNestedTransaction(), but returns false instead of throwing.

public function tryBeginNestedTransaction(
    int $flags = self::TRANSACTION_MODE_NONE,
    bool $closeCursor = false
): string|bool|null

Parameters:

ParameterTypeDescription
$flagsintTransaction flags. Defaults to self::TRANSACTION_MODE_NONE. (default self::TRANSACTION_MODE_NONE).
$closeCursorboolWhether to free the active statement cursor before starting. (default false).

Return:

string|bool|null - Returns: - string: The savepoint name when a nested transaction is created. - null: A new transaction was started successfully. - false: Failed to start a transaction or create a savepoint.


savepoint

Creates a savepoint inside the active transaction.

public function savepoint(string $name): bool

Parameters:

ParameterTypeDescription
$namestringThe name for a savepoint.

Return:

bool - Returns true on success or false on failure.

Names are cleaned before use: characters other than letters, digits and underscores are removed, purely numeric names get a tnx_ prefix, and the result is cut to 64 characters. The same cleaning is applied in commit(), rollback() and release(), so you can pass the original name to them.

Throws:


commit

Commits the active transaction. Returns true when no transaction is active.

public function commit(int $flags = 0, ?string $name = null): bool

Parameters:

ParameterTypeDescription
$flagsintNative MYSQLI_TRANS_COR_* flags (default 0).
$name?stringA savepoint name registered with savepoint(). It is passed to mysqli::commit() as the transaction name.

Return:

bool - Returns true if the transaction was successfully committed.

Throws:

To release a single savepoint, use release().


rollback

Rolls back the active transaction. Returns true when no transaction is active.

public function rollback(int $flags = 0, ?string $name = null): bool

Parameters:

ParameterTypeDescription
$flagsintNative MYSQLI_TRANS_COR_* flags (default 0).
$name?stringA savepoint name registered with savepoint(). It is passed to mysqli::rollback() as the transaction name.

Return:

bool - Returns true if the rollback was successful, otherwise false.

Throws:


release

Releases a savepoint without ending the transaction. Returns false when no transaction is active.

public function release(string $name): bool

Parameters:

ParameterTypeDescription
$namestringThe savepoint name to release.

Return:

bool - Returns true on success or false on failure.


inTransaction

Checks whether a transaction is active. The driver tracks this itself, so a transaction started with raw SQL such as exec('START TRANSACTION') is not detected.

public function inTransaction(): bool

Return:

bool - Returns true if there is an active transaction, otherwise false.


setTransactionIsolation

Sets the isolation level with SET TRANSACTION ISOLATION LEVEL. Call it before a transaction starts.

public function setTransactionIsolation(int $level = self::TRANSACTION_READ_COMMITTED): bool

Parameters:

ParameterTypeDescription
$levelintTRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ or TRANSACTION_SERIALIZABLE. TRANSACTION_MODE_NONE does nothing and returns true.

Return:

bool - Returns true on success, or false otherwise.

Throws:

TRANSACTION_READ_WRITE and TRANSACTION_READ_ONLY are not isolation levels. Pass them as flags to beginTransaction() instead.


lock

Acquires a named database lock and waits up to $timeout seconds.

public function lock(string|int $identifier, int $timeout = 300): bool

Parameters:

ParameterTypeDescription
$identifierstring&#124;intLock identifier.
$timeoutintMaximum time in seconds to wait for acquiring the lock.

Return:

bool - Return true if the lock was acquired.

Example:

if ($db->lock('daily-report', 30)) {
    try {
        // Do the work
    } finally {
        $db->unlock('daily-report');
    }
}

tryLock

Attempts to acquire a lock without waiting.

public function tryLock(string|int $identifier): bool

Parameters:

ParameterTypeDescription
$identifierstring&#124;intLock identifier.

Return:

bool - Returns true if the lock was acquired, false if it is already held or acquisition failed.

This method currently returns false whatever the outcome. The result is stored internally, so call isLocked() to find out whether the lock was acquired.


unlock

Releases a named lock.

public function unlock(string|int $identifier): bool

Parameters:

ParameterTypeDescription
$identifierstring&#124;intLock identifier.

Return:

bool - Returns true if the lock was released successfully, false otherwise.


isLocked

Checks whether a lock is held. A lock acquired or released through this driver instance is answered from memory, otherwise the database is queried.

public function isLocked(string|int $identifier): bool

Parameters:

ParameterTypeDescription
$identifierstring&#124;intLock identifier.

Return:

bool - Returns true if the lock is currently held, false if it is available.


error

Gets the last error message from the active statement, or from the connection when there is no statement.

public function error(): string

Return:

string - Returns the error information as a string.


errors

Gets statement and connection error details.

public function errors(): array

Return:

array<string,array<string,mixed>> - Returns statement and connection error details.

KeyTypeDescription
statement.errnointMySQL error number, or -1 when there is no statement.
statement.errorstring&#124;nullError message, or null.
statement.num_rowsint&#124;nullRow count of the statement, or null when there is no statement.
connection.errnointMySQL error number, or -1 when not connected.
connection.errorstring&#124;nullError message, or Connection not established.

info

Gets the parsed mysqli::$info value of the last query as key and number pairs, for example Records, Duplicates and Warnings.

public function info(): array

Return:

array<array-key,mixed> - Return ['status' => 'disconnected'] when not connected, ['status' => 'idle'] when there is no info, otherwise the parsed pairs.


setDebug

Enables or disables debug mode.

public function setDebug(bool $debug): self

Parameters:

ParameterTypeDescription
$debugboolEnable or disable debug mode.

Return:

self - Returns the instance of database driver interface.


dumpDebug

Prints the last query and its bound parameters when debug mode is on.

public function dumpDebug(): bool

Return:

bool - Return false when debug mode is off or there is no statement or result.


profiling

Starts or stops query timing. Timing is recorded only when profiling is enabled by the debug.show.performance.profiling environment setting. The driver calls it for you around each query, so you rarely need it directly.

public function profiling(
    bool $start = true,
    bool $finishedTransaction = false,
    ?string $fn = null
): void

Parameters:

ParameterTypeDescription
$startboolWhether to start profiling; false stops profiling. (default true).
$finishedTransactionboolWhether profiling is being stopped after a transaction has been committed or rolled back. (default false).
$fn?string(default null).

While a transaction is active, timing is held back until the transaction is committed or rolled back. Results are stored under Runtime::QUERY_PROFILING:

use Luminova\Runtime;

$profiling = Runtime::get(Runtime::QUERY_PROFILING);

getQueryTime

Gets the total query execution time in seconds.

public function getQueryTime(): float|int

Return:

float|int - Returns the total query execution time in seconds.


getLastQueryTime

Gets the last query execution time in seconds.

public function getLastQueryTime(): float|int

Return:

float|int - Returns the last query execution time in seconds.

Both timing methods return 0 unless profiling is enabled.


Driver differences

The MySQLi and PDO drivers share one interface, but a few behaviors differ.

AreaMySQli DriverPDO Driver
rowCount()At least 1 after a successful query() or execute().The real count from the statement, which can be 0.
BindingsCleared after each execute().Kept on the statement.
PlaceholdersNamed placeholders are converted to positional ? placeholders when named placeholder support is enabled. Repeated named placeholders require emulate_prepares to be true. When named placeholders are disabled, use positional placeholders and bind values in query order.Supports named and positional placeholders natively. Repeated named placeholders may require emulate_prepares to be true, depending on the PDO driver and prepare mode.
execute($params)Merges with values from bind() and param().Replaces the bound values.
Unknown fetch modeThrows a DatabaseException.Falls back to FETCH_OBJ.
FETCH_COLUMN, FETCH_KEY_PAIR for a single rowReturns an associative array.Native PDO result.
commit($flags, $name)$name is forwarded to mysqli::commit().Releases the named savepoint.
rollback($flags, $name)$name is forwarded to mysqli::rollback().Rolls back to the named savepoint.
inTransaction()Tracked by the driver.Native PDO::inTransaction().
getLastInsertId($name)$name is ignored.$name is passed as the sequence name.
getStatement() after fetchingReturns null.Returns the PDOStatement.
Database supportMySQL and MariaDB.MySQL, PostgreSQL, SQLite, SQL Server, Oracle, CUBRID.