Luminova Framework

PHP Luminova: PDO Database Driver

Last updated: 2026-10-26 16:50:28

Learn how to use Luminova's PDO database driver to establish database connections, execute queries, manage transactions, and access native PDO functionality.

The PdoDriver class is Luminova's PDO based database driver. It implements DatabaseDriverInterface and gives you one API for prepared statements, value binding, result fetching, transactions, savepoints, and database level locks.

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

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' => 'pdo',
    'pdo_driver' => 'mysql',
    'host'       => 'localhost',
    'port'       => 3306,
    'database'   => 'my_db',
    'username'   => 'root',
    'password'   => 'password',
]));

Configuration keys used by this driver:

KeyDefaultDescription
pdo_drivermysqlPDO driver name. Supported: mysql, pgsql, sqlite, sqlsrv, dblib, cubrid, oci. Any other value throws a DatabaseException.
hostlocalhostDatabase server host.
port3306Database server port.
database''Database name.
usernamerootDatabase username. Ignored for SQLite.
password''Database password. Ignored for SQLite.
charsetutf8mb4Connection charset. utf8 and utf-8 are converted to utf8mb4.
sqlite_pathnullPath to the SQLite file. Required when pdo_driver is sqlite.
emulate_preparestrueSets PDO::ATTR_EMULATE_PREPARES.
persistentfalseSets PDO::ATTR_PERSISTENT. Always enabled when running in the CLI.
socketfalseMySQL only. Connect through a Unix socket instead of TCP.
socket_path''MySQL only. Unix socket path.
buffered_queryfalseMySQL only. Sets PDO::MYSQL_ATTR_USE_BUFFERED_QUERY.
timeout0MySQL only. Sets PDO::ATTR_TIMEOUT in seconds when greater than zero.
commands[]MySQL only. List of SET statements to run when the connection opens.

Additional Notes

  • Error mode and fetch mode:The driver always connects with PDO::ERRMODE_EXCEPTION and PDO::FETCH_OBJ as the default fetch mode.

  • Unix socket (MySQL):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 pdo_mysql.default_socket from php.ini. A DatabaseException is thrown when neither is set.

  • Init commands (MySQL):Only SET statements are allowed in commands, any other statement throws a DatabaseException. If none of them is a SET NAMES statement, SET NAMES <charset> is added automatically.

  • SSL (MySQL):Server certificate verification is turned on in production.

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

  • Differences from MySQLi:Row counts, binding lifetime, and savepoint handling differ between the two drivers. See Driver differences in the MySQLi driver docs.


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

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

Read rows one at a time:

$db->query('SELECT id, name FROM users');

while ($row = $db->fetchNext()) {
    echo $row->name;
}

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 AbstractBaseDriver and accessed through the driver class, for example PdoDriver::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

constructor

Creates the driver from a configuration object. The PDO driver name is read from pdo_driver and lowercased. It does not connect, call connect() to open the connection.

public __construct(Luminova\Config\DatabaseConfig $config)

getInstance

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

public static getInstance(Luminova\Config\DatabaseConfig $config): DatabaseDriverInterface

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


connect

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

public connect(): bool

Return Value:

bool - Return true when connected.

Throws:

  • \Luminova\Exceptions\DatabaseException - If the PDO driver is unsupported, the SQLite path is missing, an init command is invalid, a socket path is required but missing, 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 isConnected(): bool

close

Frees the active statement, releases the PDO object, and decrements the open connection count.

public close(): void

getDriver

Gets the PDO driver name reported by PDO::ATTR_DRIVER_NAME, for example mysql.

public getDriver(): ?string

Return Value:

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


getVersion

Gets the database server version string for the active PDO driver.

public getVersion(): ?string

Return Value:

string|null - Return the version string, or null if it cannot be determined.


getConfig

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

public getConfig(?string $property): mixed

Return Value:

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 PDO object.

public getConn(): Luminova\Interface\DriverConnectionInterface

getOpenConnections

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

public static getOpenConnections(): int

exists

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

public exists(string $table): bool

Example:

if ($db->exists('users')) {
    // The table is there
}

prepare

Prepares an SQL statement and resets the previous query state. Use named placeholders such as :id.

public prepare(string $query): self

Throws:


bind

Binds a value to a named placeholder using PDOStatement::bindValue().

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

Parameters:

ParameterTypeDescription
$paramstringNamed placeholder, for example :id.
$valuemixedThe value to bind.
$typeint|nullA PARAM_* constant or a native PDO::PARAM_* value. null resolves the type from the value with getType().

Return Value:

self - Return the driver instance.

Throws:

PARAM_FLOAT is bound as a string, because PDO has no float type.


value

Alias of bind().

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

param

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

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

Example:

$status = 'active';

$db->prepare('UPDATE users SET status = :status WHERE id = :id')
    ->param(':status', $status)
    ->bind(':id', 100);

$status = 'inactive';
$db->execute();

getType

Resolves the PDO parameter type for a value.

public static getType(mixed $value): int
ValueResult
nullPDO::PARAM_NULL
boolPDO::PARAM_BOOL
intPDO::PARAM_INT
resourcePDO::PARAM_LOB
string with any byte outside tab, line breaks and printable ASCIIPDO::PARAM_LOB
everything elsePDO::PARAM_STR

The string check is byte based, so multibyte UTF-8 text is resolved as PDO::PARAM_LOB. Pass an explicit $type to bind() if you need PARAM_STR.


execute

Executes the prepared statement. When $params is given, PDO uses it as the full set of input parameters.

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

Parameters:

ParameterTypeDescription
$paramsarray|nullValues for the placeholders, keyed by name (:id) or in positional order.

Return Value:

bool - Return true on success.

Throws:


query

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

public query(string $query): self

Example:

$users = $db->query('SELECT * FROM users')->fetchAll();

exec

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

public exec(string $query): int

Return Value:

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.

Example:

$affected = $db->exec("UPDATE users SET status = 'active' WHERE last_login > NOW() - INTERVAL 30 DAY");

ok

Checks whether the last query was executed successfully.

public ok(): bool

Example:

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

if ($db->ok()) {
    $user = $db->fetchNext();
}

getResult

Retrieves a result in the shape given by $returnMode.

public getResult(int $returnMode = RETURN_ALL, int $fetchAS = FETCH_OBJ): mixed
Return modeSame as
RETURN_NEXTfetchNext($fetchAS)
RETURN_ALLfetchAll($fetchAS)
RETURN_2D_NUMgetInt()
RETURN_INTgetCount()
RETURN_IDgetLastInsertId()
RETURN_COUNTrowCount()
RETURN_COLUMNgetColumns()
RETURN_STMTgetStatement()
RETURN_RESULTThe PDOStatement, or null 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 statement.

public 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.
$fetchASintOne of FETCH_ASSOC, FETCH_BOTH, FETCH_OBJ, FETCH_COLUMN, FETCH_KEY_PAIR, FETCH_NUM, FETCH_CLASS. An unknown value falls back to FETCH_OBJ.

Return Value:

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

Throws:

With FETCH_CLASS rows are returned as stdClass. To hydrate your own class, use fetchObject() or fetchAllObject().

Example:

$db->query('SELECT id, name FROM users');
$names = $db->fetch(RETURN_ALL, FETCH_KEY_PAIR);

fetchNext

Fetches the next row.

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

Return Value:

array|object|false - Return the row, or false when no more rows are available.


getNext

Alias of fetchNext().

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

fetchAll

Fetches all remaining rows.

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

Return Value:

array|object|false - Return the rows, or false when the result is empty.


getAll

Alias of fetchAll().

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

fetchObject

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

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

Parameters:

ParameterTypeDescription
$classclass-string|nullClass to instantiate. Defaults to stdClass.
...$argumentsmixedConstructor arguments for the class.

Return Value:

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 fetchAllObject(?string $class = null, mixed ...$arguments): array

Return Value:

array - Return a list of instances, empty when there are no rows.


getColumns

Fetches all rows using a column oriented fetch mode.

public getColumns(int $mode = FETCH_COLUMN): array

Return Value:

array - Return the values of the first column by default, or an empty array.


getInt

Fetches all rows as numeric arrays.

public getInt(): array

getCount

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

public getCount(): int

Return Value:

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


getLastInsertId

Gets the ID generated by the last INSERT. Pass a sequence name for databases that use sequences, such as PostgreSQL.

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

Return Value:

mixed - Return the ID, or null when there is none or the driver is not connected.


rowCount

Gets the number of rows affected or returned by the active statement, as reported by PDOStatement::rowCount().

public rowCount(): int

columnCount

Gets the number of columns in the active result set.

public columnCount(): int

getStatement

Gets the active PDOStatement.

public getStatement(): ?PDOStatement

isStatement

Checks whether there is an active PDOStatement.

public isStatement(): bool

isResult

Checks whether the last operation was run through query() or exec() and nothing has been bound since.

public isResult(): bool

hasActiveCursor

Checks whether the active statement has columns, meaning it can return rows. This method exists on PdoDriver only.

public hasActiveCursor(): bool

free

Closes the statement cursor and clears the active statement.

public free(): void

beginTransaction

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

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

Parameters:

ParameterTypeDescription
$flagsintCombine TRANSACTION_WITH_CONSISTENT_SNAPSHOT, TRANSACTION_READ_WRITE and TRANSACTION_READ_ONLY with \|. They are sent as START TRANSACTION ....
$namestring|nullCreates a savepoint with this name after the transaction starts. Required when a transaction is already active.

Return Value:

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

Throws:

Example:

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

tryBeginTransaction

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

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

beginNestedTransaction

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

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

Parameters:

ParameterTypeDescription
$flagsintTransaction flags, used only when a new transaction starts.
$closeCursorboolFree the active statement before starting.

Return Value:

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 tryBeginNestedTransaction(
    int $flags = PdoDriver::TRANSACTION_MODE_NONE, 
    bool $closeCursor = false
): string|bool|null

savepoint

Creates a savepoint inside the active transaction.

public savepoint(string $name): bool

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, or releases a savepoint when $name is given. Returns true when no transaction is active.

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

$flags is not used by the PDO driver.

Throws:


rollback

Rolls back the active transaction, or rolls back to a savepoint when $name is given. Returns true when no transaction is active.

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

$flags is not used by the PDO driver.

Throws:


release

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

public release(string $name): bool

inTransaction

Checks whether a transaction is active, using the native PDO::inTransaction().

public inTransaction(): bool

setTransactionIsolation

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

public setTransactionIsolation(int $level = PdoDriver::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.

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 lock(string|int $identifier, int $timeout = 300): bool

The lock mechanism depends on the database: MySQL named locks, PostgreSQL advisory locks (non numeric identifiers are hashed), and for SQLite a lease table named dbms_locks, created on first use. $timeout does not apply to PostgreSQL.

Return Value:

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 tryLock(string|int $identifier): bool

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 unlock(string|int $identifier): bool

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 isLocked(string|int $identifier): bool

error

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

public error(): string

Return Value:

string - Return the message, an empty string if none, or Connection not established when not connected.


errors

Gets statement and connection error details.

public errors(): array

Return Value:

array - Return the following structure.

KeyDescription
statement.errnoSQLSTATE code, or -1 when there is no statement.
statement.errorDriver error message, or null.
statement.num_rowsRow count of the statement, or null when there is no statement.
connection.errnoSQLSTATE code, or -1 when not connected.
connection.errorDriver error message, or Connection not established.

info

Gets the parsed PDO::ATTR_CONNECTION_STATUS value as key and value pairs.

public info(): array

Return Value:

array - Return ['status' => 'disconnected'] when not connected, ['status' => 'idle'] when the driver reports nothing, otherwise the parsed pairs (empty if the status text has no key: value parts).


setDebug

Enables or disables debug mode.

public setDebug(bool $debug): self

dumpDebug

Dumps the active statement's parameters with PDOStatement::debugDumpParams() when debug mode is on.

public dumpDebug(): bool

Return Value:

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


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 profiling(bool $start = true, bool $finishedTransaction = false, ?string $fn = null): void

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 getQueryTime(): float|int

getLastQueryTime

Gets the last query execution time in seconds.

public getLastQueryTime(): float|int

Both timing methods return 0 unless profiling is enabled.