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
// Get an instance of WireDatabaseBackup
$backup = $database->backups();

This class intentionally does not have any external dependencies (other than PDO)so that it can be included by outside tools for restoring/exporting, with the main example of that being the ProcessWire installer.

The recommended way to access these backup methods is via the $database API variable method $database->backups(), which returns a WireDatabaseBackup instance, however you can also initialize the class manually if you prefer, like this:

// determine where backups will go (should NOT be web accessible)
$backupPath = $config->paths->assets . 'backups/';

// create a new WireDatabaseBackup instance
$backup = new WireDatabaseBackup($backupPath);

// Option 1: set the already-connected DB connection
$backup->setDatabase($this->database);

// Option 2: OR provide a Config object that contains the DB connection info
$backup->setDatabaseConfig($this->config);

Backup the database

$file = $backup->backup();
if($file) {
  echo "Backed up to: $file";
} else {
  echo "Backup failed: " . implode("<br>", $backup->errors());
}

Restore a database

$success = $backup->restore($file);
if($success) {
  echo "Restored database from file: $file";
} else {
  echo "Restore failed: " . implode("<br>", $backup->errors());
}

Click any linked item for full usage details and examples. Hookable methods are indicated with the icon.

Show $var?     Show args?       Only hookable?    

Initialization

It’s not typically necessary to call these initialization methods unless doing manual initialization.

Advanced

NameReturnSummary 
$backup->getDatabase()
PDO

Get current database connection, initiating the connection if not yet active

 
$backup->restoreMerge(string $filename1, string $filename2, array $options)
bool

Restore from 2 SQL files while resolving table differences (think of it as array_merge for a DB restore)

 

Common

NameReturnSummary 
$backup->dropAllTables()
int

Drop all tables from database

 

API reference based on ProcessWire core version 3.0.261