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.

Common Rules
  • Prefer prepared statements for values; use quote() only when prepared statements are not practical.
  • Use escapeTable(), escapeCol() and escapeTableCol() 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) {
    // ...
}
Connection

pdo()

  • Arguments: pdo($type = null)
  • Returns: \PDO
  • Purpose: Get the underlying PDO connection. Omit $type for 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 for setAttribute()
  • 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: $type may be 'writer', 'reader', or omitted for both/current use.
$database->reset();
$database->close('writer');
Queries

prepare()

  • Arguments: prepare($statement, $driver_options = [], $note = '')
  • Returns: \PDOStatement|WireDatabasePDOStatement
  • 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:

ValueBehavior
arrayPassed through as PDO driver options
trueRequest a WireDatabasePDOStatement
stringTreated 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 throw

query()

  • 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

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

Schema methods inspect database tables, columns and indexes.

getTables()

  • Arguments: getTables($allowCache = true)
  • Returns: array of table names
$tables = $database->getTables(false); // bypass cache

tableExists()

  • 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 info

Verbose modes:

ValueDescription
falseColumn names only
true or 1Simplified verbose info indexed by column name
2Raw MySQL column information
3Column types as used in a CREATE TABLE statement
stringOne 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 for renameColumns()
  • 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',
]);
Sanitization

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, or column string
$field = $database->escapeTableCol('pages.name');

isOperator()

  • Arguments: isOperator($str, $operatorType = WireDatabasePDO::operatorTypeAny, $get = false)
  • Returns: bool|string
  • Purpose: Validate comparison or bitwise SQL operators.
if($database->isOperator($operator, WireDatabasePDO::operatorTypeComparison)) {
    // =, !=, <, <=, >, >=, <>
}

Operator type constants:

ConstantDescription
WireDatabasePDO::operatorTypeComparisonComparison operators only
WireDatabasePDO::operatorTypeBitwiseBitwise operators only
WireDatabasePDO::operatorTypeAnyComparison or bitwise operators

escapeOperator()

  • Arguments: escapeOperator($operator, $operatorType = WireDatabasePDO::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 LIKE values.
$like = '%' . $database->escapeLike($term) . '%';
Info

getVersion()

  • Arguments: getVersion($getNumberOnly = false)
  • Returns: MySQL/MariaDB version string.

getServerType()

  • Returns: server type string such as MySQL, MariaDB, or Percona.

getRegexEngine()

  • Returns: ICU or HenrySpencer.

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.
Query Log

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);         // stop

Argument behavior:

$sql valueBehavior
omitted or ''Return current log array
trueReset and start logging
1Start logging without reset
falseStop logging
stringAppend SQL to log when logging is active

Core automatically populates this log when ProcessWire debug mode is active.

Backups

backups()

  • Returns: WireDatabaseBackup
  • Purpose: Create a backup helper instance configured for this database.
$backups = $database->backups();

See WireDatabaseBackup for backup and restore operations.

API reference: methods

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 WireDatabasePDO class also inherits all the methods and properties of: Wire.

Show $var?     Show args?       Only hookable?    

Queries

Schema

NameReturnSummary 
$database->columnExists(string $table)
bool array

Does the given column exist in given table?

 
$database->getCharset()
string

Get current database charset (lowercase)

 
$database->getColumns(string $table)
array

Get all columns from given table

 
$database->getEngine()
string

Get current database engine (lowercase)

 
$database->getIndexes(string $table)
array

Get all indexes from given table

 
$database->getMaxIndexLength()
int

Get max length allowed for a fully indexed varchar column in ProcessWire

 
$database->getPrimaryKey(string $table)
string array

Get column(s) or info for given table’s primary key/index

 
$database->getTables()
array

Get array of all tables in this database.

 
$database->indexExists(string $table, string $indexName)
bool array

Does table have an index with given name?

 
$database->renameColumn(string $table, string $oldName, string $newName)
bool

Rename a table column without changing type

 
$database->renameColumns(string $table, array $columns)
int

Rename table columns without changing type

 
$database->tableExists(string $table)
bool

Does the given table exist in this database?

 

Connection

NameReturnSummary 
$database->closeConnection()
None

Close the PDO connection

 
$database->errorCode()
string

Fetch the SQLSTATE associated with the last operation on the statement handle

 
$database->errorInfo()
array

Fetch extended error information associated with the last operation on the database handle

 
$database->getAttribute(int $attribute)
mixed

Retrieve a database connection attribute

 
$database->reset()
self

Reset the current PDO connection(s)

 
$database->setAttribute(int $attribute, mixed $value)
bool

Sets an attribute on the database handle

 

Custom

NameReturnSummary 
$database->backups()
WireDatabaseBackup

Retrieve new instance of WireDatabaseBackups ready to use with this connection

 
$database->queryLog()
array bool

Log a query, start/stop query logging, or return logged queries

 
$database->sqlMode()
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, WireDatabasePDO also inherits the methods and properties of these classes:

API reference based on ProcessWire core version 3.0.261