WireDatabasePDO / $database
$database is ProcessWire's PDO-based database API variable
It wraps PHP's native
PDO class with ProcessWire-specific helpers for queries, transactions, schema
inspection, identifier sanitization, query logging, and database metadata.
Most site code should use higher-level ProcessWire APIs such as $pages, $fields,
and $templates where possible. Use $database when you need direct SQL access.
- Prefer prepared statements for values; use
quote()only when prepared statements are not practical. - Use
escapeTable(),escapeCol()andescapeTableCol()for identifiers only, not values. - Do not concatenate unsanitized input into SQL.
- Use
execute($query, false)only when you intend to handle query failure yourself. - Close cursors or fully consume statements before running dependent queries when needed.
- Use transactions only when
allowTransaction()returns true.
$query = $database->prepare("SELECT id, name FROM pages WHERE templates_id=:template");
$query->bindValue(':template', $template->id, \PDO::PARAM_INT);
$database->execute($query);
foreach($query as $row) {
// ...
}pdo()
- Arguments:
pdo($type = null) - Returns:
\PDO - Purpose: Get the underlying PDO connection. Omit
$typefor the writer connection.
$pdo = $database->pdo();The $database->pdo property is an alias for $database->pdo().
getAttribute() / setAttribute()
- Arguments:
getAttribute($attribute),setAttribute($attribute, $value) - Returns: mixed for
getAttribute(), bool forsetAttribute() - Purpose: Proxy to PDO connection attributes.
$driver = $database->getAttribute(\PDO::ATTR_DRIVER_NAME);errorCode() / errorInfo()
- Returns: Last PDO error code or error info from the last used connection.
reset() / close()
- Arguments:
reset($type = null),close($type = null) - Returns:
$database - Purpose: Close or re-create writer/reader PDO connections.
- Types:
$typemay be'writer','reader', or omitted for both/current use.
$database->reset();
$database->close('writer');prepare()
- Arguments:
prepare($statement, $driver_options = [], $note = '') - Returns:
\PDOStatement|WireDatabase P D OStatement - Purpose: Prepare SQL for bound parameters.
$query = $database->prepare("SELECT * FROM pages WHERE id=:id");
$query->bindValue(':id', 1234, \PDO::PARAM_INT);
$database->execute($query);The $driver_options argument may be:
| Value | Behavior |
|---|---|
| array | Passed through as PDO driver options |
true | Request a Wire |
| string | Treated as the debug $note argument |
execute()
- Arguments:
execute(\PDOStatement $query, $throw = true, $maxTries = 3) - Returns: bool
- Purpose: Execute a prepared statement with ProcessWire retry/error handling.
$ok = $database->execute($query);
$ok = $database->execute($query, false); // return false rather than throwquery()
- Arguments:
query($statement, $note = '') - Returns:
\PDOStatement - Purpose: Execute SQL and return a result set.
$rows = $database->query("SELECT id FROM pages LIMIT 10");
foreach($rows as $row) {
echo $row['id'];
}exec()
- Arguments:
exec($statement, $note = '') - Returns: int|bool
- Purpose: Execute SQL and return the number of affected rows when available.
If given a PDOStatement, it delegates to
execute().
$n = $database->exec("UPDATE pages SET modified=modified WHERE id=1234");lastInsertId()
- Arguments:
lastInsertId($name = null) - Returns: string
- Purpose: Return the last auto-increment ID from the writer connection.
Transactions are available when the current database engine/table supports them.
if($database->allowTransaction()) {
$database->beginTransaction();
try {
$database->exec("UPDATE ...");
$database->commit();
} catch(\Exception $e) {
$database->rollBack();
throw $e;
}
}beginTransaction()
- Returns: bool
- Purpose: Begin a writer transaction and disable reader use while active.
inTransaction()
- Returns: bool
- Purpose: Check whether the writer connection is currently in a transaction.
commit()
- Returns: bool
- Purpose: Commit the active transaction. Returns false if not in a transaction.
rollBack()
- Returns: bool
- Purpose: Roll back the active transaction. Returns false if not in a transaction.
supportsTransaction() / allowTransaction()
- Arguments:
supportsTransaction($table = ''),allowTransaction($table = '') - Returns: bool
- Purpose: Determine whether transactions are supported and currently allowed.
Schema methods inspect database tables, columns and indexes.
getTables()
- Arguments:
getTables($allowCache = true) - Returns: array of table names
$tables = $database->getTables(false); // bypass cachetableExists()
- Arguments:
tableExists($table) - Returns: bool
getColumns()
- Arguments:
getColumns($table, $verbose = false) - Returns: array
- Purpose: Get column names or verbose column info.
$names = $database->getColumns('pages');
$info = $database->getColumns('pages', true); // indexed by column name
$name = $database->getColumns('pages', 'name'); // one column infoVerbose modes:
| Value | Description |
|---|---|
false | Column names only |
true or 1 | Simplified verbose info indexed by column name |
2 | Raw MySQL column information |
3 | Column types as used in a CREATE TABLE statement |
| string | One column's verbose info |
columnExists()
- Arguments:
columnExists($table, $column = '', $getInfo = false) - Returns: bool|array
$ok = $database->columnExists('pages', 'name');
$ok = $database->columnExists('pages.name');
$info = $database->columnExists('pages', 'name', true);getIndexes()
- Arguments:
getIndexes($table, $verbose = false) - Returns: array
$indexes = $database->getIndexes('pages');
$info = $database->getIndexes('pages', true);
$primary = $database->getIndexes('pages.PRIMARY', true);indexExists()
- Arguments:
indexExists($table, $indexName, $getInfo = false) - Returns: bool|array
getPrimaryKey()
- Arguments:
getPrimaryKey($table, $verbose = false) - Returns: string|array
- Purpose: Return primary key column(s), or verbose primary-key info.
renameColumn() / renameColumns()
- Arguments:
renameColumn($table, $oldName, $newName),renameColumns($table, array $columns) - Returns: bool for
renameColumn(), int count forrenameColumns() - Purpose: Rename columns without changing type.
$database->renameColumn('my_table', 'old_name', 'new_name');
$database->renameColumns('my_table', [
'old_a' => 'new_a',
'old_b' => 'new_b',
]);Use these helpers when building SQL identifiers or operator strings from dynamic values. They sanitize identifiers; they do not quote identifiers with backticks.
escapeTable() / escapeCol()
- Arguments:
escapeTable($table),escapeCol($col) - Returns: string containing only
_a-zA-Z0-9
$table = $database->escapeTable($inputName);
$col = $database->escapeCol($inputColumn);escapeTableCol()
- Arguments:
escapeTableCol($str) - Returns: sanitized
table.column,table, orcolumnstring
$field = $database->escapeTableCol('pages.name');isOperator()
- Arguments:
isOperator($str, $operatorType = WireDatabase P D O::operatorTypeAny, $get = false) - Returns: bool|string
- Purpose: Validate comparison or bitwise SQL operators.
if($database->isOperator($operator, WireDatabasePDO::operatorTypeComparison)) {
// =, !=, <, <=, >, >=, <>
} Operator type constants:
| Constant | Description |
|---|---|
Wire | Comparison operators only |
Wire | Bitwise operators only |
Wire | Comparison or bitwise operators |
escapeOperator()
- Arguments:
escapeOperator($operator, $operatorType = WireDatabase P D O::operatorTypeComparison, $default = '=') - Returns: valid operator or fallback
quote()
- Arguments:
quote($str) - Returns: quoted and escaped string value, including surrounding quotes.
$sql = "name=" . $database->quote($name);Prefer prepared statements for values whenever possible.
escapeStr()
- Arguments:
escapeStr($str) - Returns: escaped string without surrounding quotes.
escapeLike()
- Arguments:
escapeLike($like) - Returns: escaped string suitable for SQL
LIKEvalues.
$like = '%' . $database->escapeLike($term) . '%';getVersion()
- Arguments:
getVersion($getNumberOnly = false) - Returns: MySQL/MariaDB version string.
getServerType()
- Returns: server type string such as
MySQL,MariaDB, orPercona.
getRegexEngine()
- Returns:
ICUorHenrySpencer.
getEngine()
- Returns: current configured database engine in lowercase.
getCharset()
- Returns: current configured database charset in lowercase.
getVariable()
- Arguments:
getVariable($name, $cache = true, $sub = true) - Returns: string|null
- Purpose: Retrieve a MySQL/MariaDB variable.
$version = $database->getVariable('version');getMaxIndexLength()
- Returns: int max length allowed for a fully indexed varchar column.
getTime()
- Arguments:
getTime($getTimestamp = false) - Returns: ISO datetime string or UNIX timestamp.
$now = $database->getTime();
$ts = $database->getTime(true);getStopwords() / isStopword()
- Arguments:
getStopwords($engine = '', $flip = false),isStopword($word, $engine = '') - Returns: array or bool
- Purpose: Get or check fulltext stopwords for MyISAM/InnoDB.
queryLog()
- Arguments:
queryLog($sql = '', $note = '') - Returns: array|bool
- Purpose: Start, stop, reset, retrieve, or append to the in-memory query log.
$database->queryLog(true); // reset and start
$database->query("SELECT 1", "note");
$log = $database->queryLog(); // retrieve
$database->queryLog(false); // stopArgument behavior:
$sql value | Behavior |
|---|---|
omitted or '' | Return current log array |
true | Reset and start logging |
1 | Start logging without reset |
false | Stop logging |
| string | Append SQL to log when logging is active |
Core automatically populates this log when ProcessWire debug mode is active.
backups()
- Returns:
WireDatabaseBackup - Purpose: Create a backup helper instance configured for this database.
$backups = $database->backups();See WireDatabaseBackup for backup and restore operations.
ProcessWire creates the database connection automatically at boot and this is available from the $database API variable. If you want to create a new connection on your own, choose either option A or B below:
// The following are required to construct a WireDatabasePDO
$dsn = 'mysql:dbname=mydb;host=myhost;port=3306';
$username = 'username';
$password = 'password';
$driver_options = []; // optional
// Construct option A
$db = new WireDatabasePDO($dsn, $username, $password, $driver_options);
// Construct option B
$db = new WireDatabasePDO([
'dsn' => $dsn,
'user' => $username,
'pass' => $password,
'options' => $driver_options, // optional
'reader' => [ // optional
'dsn' => '…',
…
],
…
]); Click any linked item for full usage details and examples. Hookable methods are indicated with the icon. In addition to those shown below, the Wire class also inherits all the methods and properties of: Wire.
Queries
| Name | Return | Summary | |
|---|---|---|---|
$database->exec() $database->exec($statement) $database->exec($statement, string $note = '') | bool int | Execute an SQL statement string | |
$database->execute() $database->execute(\PDOStatement $query) $database->execute(\PDOStatement $query, bool $throw = true, int $maxTries = 3) | bool | Execute a PDO statement, with retry and error handling | |
$database->lastInsertId() $database->lastInsertId() $database->lastInsertId($name = null) | string | Returns the ID of the last inserted row or sequence value | |
$database->prepare() $database->prepare(string $statement) $database->prepare(string $statement, $driver_options = [], string $note = '') | PDOStatement Wire | Prepare an SQL statement for accepting bound parameters | |
$database->query() $database->query(string $statement) $database->query(string $statement, string $note = '') | PDOStatement | Executes an SQL statement, returning a result set as a PDOStatement object |
Transactions
| Name | Return | Summary | |
|---|---|---|---|
$database->allowTransaction() $database->allowTransaction() $database->allowTransaction(string $table = '') | bool | Allow a new transaction to begin right now? (i.e. supported and not already in one) | |
$database->beginTransaction() $database->beginTransaction() $database->beginTransaction() | bool | Initiates a transaction | |
$database->commit() $database->commit() $database->commit() | bool | Commits a transaction | |
$database->inTransaction() $database->inTransaction() $database->inTransaction() | bool | Checks if inside a transaction | |
$database->rollBack() $database->rollBack() $database->rollBack() | bool | Rolls back a transaction | |
$database->supportsTransaction() $database->supportsTransaction() $database->supportsTransaction(string $table = '') | bool | Are transactions available with current DB engine (or table)? |
Schema
Info
Sanitization
Connection
| Name | Return | Summary | |
|---|---|---|---|
$database->closeConnection() $database->closeConnection() $database->closeConnection() | None | Close the PDO connection | |
$database->errorCode() $database->errorCode() $database->errorCode() | string | Fetch the SQLSTATE associated with the last operation on the statement handle | |
$database->errorInfo() $database->errorInfo() $database->errorInfo() | array | Fetch extended error information associated with the last operation on the database handle | |
$database->getAttribute() $database->getAttribute(int $attribute) $database->getAttribute(int $attribute) | mixed | Retrieve a database connection attribute | |
$database->reset() $database->reset() $database->reset($type = null) | self | Reset the current PDO connection(s) | |
$database->setAttribute() $database->setAttribute(int $attribute, mixed $value) $database->setAttribute(int $attribute, mixed $value) | bool | Sets an attribute on the database handle |
Custom
| Name | Return | Summary | |
|---|---|---|---|
$database->backups() $database->backups() $database->backups() | WireDatabaseBackup | Retrieve new instance of WireDatabaseBackups ready to use with this connection | |
$database->queryLog() $database->queryLog() $database->queryLog($sql = '', string $note = '') | array bool | Log a query, start/stop query logging, or return logged queries | |
$database->sqlMode() $database->sqlMode() $database->sqlMode(string $action = 'get', string $mode = '', string $minVersion = '', $pdo = null) | string bool | Get SQL mode, set SQL mode, add to existing SQL mode, or remove from existing SQL mode |
Additional methods and properties
In addition to the methods and properties above, Wire
API reference based on ProcessWire core version 3.0.261