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.
// 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.
Actions
| Name | Return | Summary | |
|---|---|---|---|
$backup->backup() $backup->backup() $backup->backup(array $options = []) | string | Perform a database export/dump | |
$backup->restore() $backup->restore(string $filename) $backup->restore(string $filename, array $options = []) | true | Restore/import a MySQL database dump file |
Reporting
| Name | Return | Summary | |
|---|---|---|---|
$backup->error() $backup->error() $backup->error(string $str = '') | string | Add an error and return last error | |
$backup->errors() $backup->errors() $backup->errors(bool $reset = false) | array | Return all error messages that occurred | |
$backup->getAllTables() $backup->getAllTables() $backup->getAllTables(bool $count = false, bool $cache = true) | array | Get array of all table names | |
$backup->getFileInfo() $backup->getFileInfo(string $filename) $backup->getFileInfo(string $filename) | array | Get information about a backup file | |
$backup->getFiles() $backup->getFiles() $backup->getFiles(bool $getObjects = false) | array \SplFileInfo | Return array of all backup files | |
$backup->getPath() $backup->getPath() $backup->getPath() | string | Get path where database files are stored | |
$backup->notes() $backup->notes() $backup->notes(bool $reset = false) | array | Get all notes |
Initialization
It’s not typically necessary to call these initialization methods unless doing manual initialization.
| Name | Return | Summary | |
|---|---|---|---|
$backup->setDatabase() $backup->setDatabase($database) $backup->setDatabase($database) | None | Set the PDO database connection | |
$backup->setDatabaseConfig() $backup->setDatabaseConfig($config) $backup->setDatabaseConfig($config) | $this | Set the database configuration information | |
$backup->setPath() $backup->setPath(string $path) $backup->setPath(string $path) | $this | Set path where database files are stored |
Advanced
| Name | Return | Summary | |
|---|---|---|---|
$backup->getDatabase() $backup->getDatabase() $backup->getDatabase() | PDO | Get current database connection, initiating the connection if not yet active | |
$backup->restoreMerge() $backup->restoreMerge(string $filename1, string $filename2, array $options) $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
| Name | Return | Summary | |
|---|---|---|---|
$backup->dropAllTables() $backup->dropAllTables() $backup->dropAllTables() | int | Drop all tables from database |
API reference based on ProcessWire core version 3.0.261