API Reference

Class and method documentation for WPZylos Database — generated from source code.

Connection

WPZylos\Framework\Database\Connection

The main database wrapper. Wraps WordPress $wpdb with plugin-scoped table naming and safe query methods. All queries use $wpdb->prepare() internally.

Constructor

public function __construct(ContextInterface $context, ?\wpdb $database = null)
ParameterTypeDescription
$contextContextInterfacePlugin context (provides table name prefixing)
$database\wpdb|nullOptional wpdb instance (defaults to $GLOBALS['wpdb'])

Query Builder Entry Point

table()

Create a QueryBuilder instance scoped to a table.

public function table(string $name, string $scope = 'site'): QueryBuilder
ParameterTypeDefaultDescription
$namestringTable name without plugin prefix
$scopestring'site''site' or 'network'

Returns: QueryBuilder


Raw wpdb Access

wpdb()

Get the underlying \wpdb instance.

public function wpdb(): \wpdb

Returns: \wpdb


charsetCollate()

Get the charset collation string for CREATE TABLE statements.

public function charsetCollate(): string

Returns: string — e.g. DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci


Raw Query Methods

query()

Execute a raw SQL query with prepared placeholders.

public function query(string $query, mixed ...$args): bool|int
ParameterTypeDescription
$querystringSQL query with %s, %d, %f placeholders
...$argsmixedValues for placeholders

Returns: bool|int — Number of rows affected, or false on error.


getRow()

Get a single row from a raw query.

public function getRow(string $query, mixed ...$args): ?object
ParameterTypeDescription
$querystringSQL query with placeholders
...$argsmixedValues for placeholders

Returns: object|null


getResults()

Get multiple rows from a raw query.

public function getResults(string $query, mixed ...$args): array
ParameterTypeDescription
$querystringSQL query with placeholders
...$argsmixedValues for placeholders

Returns: array<object> — Empty array if no results.


getVar()

Get a single scalar value from a raw query.

public function getVar(string $query, mixed ...$args): ?string
ParameterTypeDescription
$querystringSQL query with placeholders
...$argsmixedValues for placeholders

Returns: string|null


CRUD Methods

insert()

Insert a row into a table.

public function insert(string $table, array $data, ?array $format = null): int|false
ParameterTypeDescription
$tablestringFull table name (including prefix)
$dataarray<string, mixed>Column => value pairs
$formatstring[]|nullOptional format array (%s, %d, %f)

Returns: int|false — Insert ID on success, false on failure.


update()

Update rows in a table.

public function update(
    string $table,
    array $data,
    array $where,
    ?array $format = null,
    ?array $whereFormat = null
): int|false
ParameterTypeDescription
$tablestringFull table name
$dataarray<string, mixed>Column => value pairs to update
$wherearray<string, mixed>WHERE conditions (column => value)
$formatstring[]|nullFormat array for $data
$whereFormatstring[]|nullFormat array for $where

Returns: int|false — Rows affected, or false on error.


delete()

Delete rows from a table.

public function delete(string $table, array $where, ?array $whereFormat = null): int|false
ParameterTypeDescription
$tablestringFull table name
$wherearray<string, mixed>WHERE conditions (column => value)
$whereFormatstring[]|nullFormat array for $where

Returns: int|false — Rows affected, or false on error.


Convenience Methods

find()

Find a single row by primary key.

public function find(string $table, int|string $id, string $primaryKey = 'id'): ?object
ParameterTypeDefaultDescription
$tablestringFull table name
$idint|stringPrimary key value
$primaryKeystring'id'Primary key column name

Returns: object|null


insertGetId()

Insert a row and return the insert ID.

public function insertGetId(string $table, array $data, ?array $format = null): int
ParameterTypeDescription
$tablestringFull table name
$dataarray<string, mixed>Column => value pairs
$formatstring[]|nullOptional format array

Returns: int — The insert ID.


Transaction Methods

beginTransaction()

Start a database transaction.

public function beginTransaction(): bool

Returns: bool


commit()

Commit the current transaction.

public function commit(): bool

Returns: bool


rollback()

Roll back the current transaction.

public function rollback(): bool

Returns: bool


transaction()

Execute a callback within a database transaction. Automatically commits on success, rolls back on exception.

public function transaction(callable $callback): mixed
ParameterTypeDescription
$callbackcallableCallback to execute inside the transaction

Returns: mixed — The return value of $callback.

Throws: \Throwable — Re-throws any exception after rolling back.


Error / Status Methods

lastInsertId()

Get the ID generated by the last INSERT query.

public function lastInsertId(): int

Returns: int


lastError()

Get the last database error message.

public function lastError(): string

Returns: string — Empty string if no error.


hasError()

Check if the last query produced an error.

public function hasError(): bool

Returns: bool


rowsAffected()

Get the number of rows affected by the last query.

public function rowsAffected(): int

Returns: int



QueryBuilder

WPZylos\Framework\Database\QueryBuilder

Fluent interface for building SELECT, INSERT, UPDATE, and DELETE queries. Created via Connection::table(). All queries use $wpdb->prepare() internally.

Constructor

public function __construct(Connection $connection, string $table)
ParameterTypeDescription
$connectionConnectionDatabase connection
$tablestringFull table name (validated against identifier pattern)

Throws: \InvalidArgumentException if the table name is invalid.

Note: You don't call this directly — use Connection::table() instead.


Column Selection

select()

Set which columns to select.

public function select(string|array $columns = ['*']): static
ParameterTypeDescription
$columnsstring|string[]Column names, or variadic strings

Returns: static

// Array syntax
$db->table('users')->select(['id', 'name'])->get();

// Variadic syntax
$db->table('users')->select('id', 'name', 'email')->get();

Where Clauses

where()

Add a WHERE condition (all conditions are joined with AND).

public function where(string $column, mixed $operator, mixed $value = null): static
ParameterTypeDescription
$columnstringColumn name
$operatormixedOperator (=, >, <, etc.) or value if 2-arg
$valuemixedValue (when using 3-arg form)

Returns: static

// 2-arg form (defaults to '=')
$db->table('users')->where('status', 'active')->get();

// 3-arg form
$db->table('products')->where('price', '>', 100)->get();

whereIn()

Add a WHERE IN clause.

public function whereIn(string $column, array $values): static
ParameterTypeDescription
$columnstringColumn name
$valuesarrayArray of values

Returns: static

If $values is empty, the query is forced to return no results.

$db->table('users')->whereIn('id', [1, 2, 3])->get();

Ordering & Pagination

orderBy()

Add an ORDER BY clause.

public function orderBy(string $column, string $direction = 'ASC'): static
ParameterTypeDefaultDescription
$columnstringColumn name (validated)
$directionstring'ASC''ASC' or 'DESC'

Returns: static


limit()

Set the maximum number of rows to return.

public function limit(int $limit): static

Returns: static


offset()

Set the row offset for pagination.

public function offset(int $offset): static

Returns: static


Executing Queries

get()

Execute the SELECT query and return all matching rows.

public function get(): array

Returns: array<object> — Empty array if no results.


first()

Execute the SELECT query and return only the first row. Automatically sets LIMIT 1.

public function first(): ?object

Returns: object|null


count()

Execute a COUNT(*) query and return the count.

public function count(): int

Returns: int


toSql()

Get the raw SQL string (for debugging/testing). Does not execute the query.

public function toSql(): string

Returns: string — The SQL query with %s/%d placeholders.


Mutation Methods

insert()

Insert a row into the table.

public function insert(array $data): int|false
ParameterTypeDescription
$dataarray<string, mixed>Column => value pairs

Returns: int|false — Insert ID on success, false on failure.


update()

Update rows matching the current WHERE conditions.

public function update(array $data): int|false
ParameterTypeDescription
$dataarray<string, mixed>Column => value pairs

Returns: int|false — Rows affected, or false on error.

Note: Only = conditions from where() are used for the underlying $wpdb->update() call.


delete()

Delete rows matching the current WHERE conditions.

public function delete(): int|false

Returns: int|false — Rows affected, or false on error.

Note: Only = conditions from where() are used for the underlying $wpdb->delete() call.



DatabaseServiceProvider

WPZylos\Framework\Database\DatabaseServiceProvider

Extends WPZylos\Framework\Core\ServiceProvider. Registers the database Connection as a singleton in the application container.

register()

public function register(ApplicationInterface $app): void

Registered Bindings

BindingTypeResolves To
Connection::classSingletonConnection instance
'db'SingletonSame Connection instance (alias)

Usage

// Resolve by class name
$db = $app->make(Connection::class);

// Resolve by alias
$db = $app->make('db');