Database abstraction layer

Allow the use of different database servers using the same code base.

Drupal provides a database abstraction layer to provide developers with the ability to support multiple database servers easily. The intent of this layer is to preserve the syntax and power of SQL as much as possible, but also allow developers a way to leverage more complex functionality in a unified way. It also provides a structured interface for dynamically constructing queries when appropriate, and enforcing security checks and similar good practices.

The system is built atop PHP's PDO (PHP Data Objects) database API and inherits much of its syntax and semantics.

Most Drupal database SELECT queries are performed by a call to db_query() or db_query_range(). Module authors should also consider using the PagerDefault Extender for queries that return results that need to be presented on multiple pages, and the Tablesort Extender for generating appropriate queries for sortable tables.

For example, one might wish to return a list of the most recent 10 nodes authored by a given user. Instead of directly issuing the SQL query

SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid LIMIT 0, 10;

one would instead call the Drupal functions:

$result = db_query_range('SELECT n.nid, n.title, n.created
  FROM {node} n WHERE n.uid = :uid', 0, 10, array(':uid' => $uid));
foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.

Curly braces are used around "node" to provide table prefixing via DatabaseConnection::prefixTables(). The explicit use of a user ID is pulled out into an argument passed to db_query() so that SQL injection attacks from user input can be caught and nullified. The LIMIT syntax varies between database servers, so that is abstracted into db_query_range() arguments. Finally, note the PDO-based ability to iterate over the result set using foreach ().

All queries are passed as a prepared statement string. A prepared statement is a "template" of a query that omits literal or variable values in favor of placeholders. The values to place into those placeholders are passed separately, and the database driver handles inserting the values into the query in a secure fashion. That means you should never quote or string-escape a value to be inserted into the query.

There are two formats for placeholders: named and unnamed. Named placeholders are strongly preferred in all cases as they are more flexible and self-documenting. Named placeholders should start with a colon ":" and can be followed by one or more letters, numbers or underscores.

Named placeholders begin with a colon followed by a unique string. Example:

SELECT nid, title FROM {node} WHERE uid=:uid;

":uid" is a placeholder that will be replaced with a literal value when the query is executed. A given placeholder label cannot be repeated in a given query, even if the value should be the same. When using named placeholders, the array of arguments to the query must be an associative array where keys are a placeholder label (e.g., :uid) and the value is the corresponding value to use. The array may be in any order.

Unnamed placeholders are simply a question mark. Example:

SELECT nid, title FROM {node} WHERE uid=?;

In this case, the array of arguments must be an indexed array of values to use in the exact same order as the placeholders in the query.

Note that placeholders should be a "complete" value. For example, when running a LIKE query the SQL wildcard character, %, should be part of the value, not the query itself. Thus, the following is incorrect:

SELECT nid, title FROM {node} WHERE title LIKE :title%;

It should instead read:

SELECT nid, title FROM {node} WHERE title LIKE :title;

and the value for :title should include a % as appropriate. Again, note the lack of quotation marks around :title. Because the value is not inserted into the query as one big string but as an explicitly separate value, the database server knows where the query ends and a value begins. That is considerably more secure against SQL injection than trying to remember which values need quotation marks and string escaping and which don't.

INSERT, UPDATE, and DELETE queries need special care in order to behave consistently across all different databases. Therefore, they use a special object-oriented API for defining a query structurally. For example, rather than:

INSERT INTO node (nid, title, body) VALUES (1, 'my title', 'my body');

one would instead write:

$fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');

This method allows databases that need special data type handling to do so, while also allowing optimizations such as multi-insert queries. UPDATE and DELETE queries have a similar pattern.

Drupal also supports transactions, including a transparent fallback for databases that do not support transactions. To start a new transaction, simply call $txn = db_transaction(); in your own code. The transaction will remain open for as long as the variable $txn remains in scope. When $txn is destroyed, the transaction will be committed. If your transaction is nested inside of another then Drupal will track each transaction and only commit the outer-most transaction when the last transaction object goes out out of scope, that is, all relevant queries completed successfully.


function my_transaction_function() {
  // The transaction opens here.
  $txn = db_transaction();

  try {
    $id = db_insert('example')
        'field1' => 'mystring',
        'field2' => 5,


    return $id;
  catch (Exception $e) {
    // Something went wrong somewhere, so roll back now.
    // Log the exception to watchdog.
    watchdog_exception('type', $e);

  // $txn goes out of scope here.  Unless the transaction was rolled back, it
  // gets automatically committed here.

function my_other_function($id) {
  // The transaction is still open here.

  if ($id % 2 == 0) {
      ->condition('id', $id)
      ->fields(array('field2' => 10))



Databaseincludes/database/database.incPrimary front-controller for the database system.
DatabaseConditionincludes/database/query.incGeneric class for a series of conditions in a query.
DatabaseConnectionincludes/database/database.incBase Database API class.
DatabaseConnectionNotDefinedExceptionincludes/database/database.incException thrown if an undefined database connection is requested.
DatabaseConnection_sqliteincludes/database/sqlite/database.incSpecific SQLite implementation of DatabaseConnection.
DatabaseDriverNotSpecifiedExceptionincludes/database/database.incException thrown if no driver is specified for a database connection.
DatabaseStatementBaseincludes/database/database.incDefault implementation of DatabaseStatementInterface.
DatabaseStatementEmptyincludes/database/database.incEmpty implementation of a database statement.
DatabaseStatementPrefetchincludes/database/prefetch.incAn implementation of DatabaseStatementInterface that prefetches all data.
DatabaseStatement_sqliteincludes/database/sqlite/database.incSpecific SQLite implementation of DatabaseConnection.
DatabaseTransactionincludes/database/database.incA wrapper class for creating and managing database transactions.
DatabaseTransactionCommitFailedExceptionincludes/database/database.incException thrown when a commit() function fails.
DatabaseTransactionExplicitCommitNotAllowedExceptionincludes/database/database.incException to deny attempts to explicitly manage transactions.
DatabaseTransactionNameNonUniqueExceptionincludes/database/database.incException thrown when a savepoint or transaction name occurs twice.
DatabaseTransactionNoActiveExceptionincludes/database/database.incException for when popTransaction() is called with no active transaction.
DatabaseTransactionOutOfOrderExceptionincludes/database/database.incException thrown when a rollback() resulted in other active transactions being rolled-back.
DeleteQueryincludes/database/query.incGeneral class for an abstracted DELETE operation.
DeleteQuery_sqliteincludes/database/sqlite/query.incSQLite specific implementation of DeleteQuery.
FieldsOverlapExceptionincludes/database/database.incException thrown if an insert query specifies a field twice.
InsertQueryincludes/database/query.incGeneral class for an abstracted INSERT query.
InsertQuery_sqliteincludes/database/sqlite/query.incSQLite specific implementation of InsertQuery.
InvalidMergeQueryExceptionincludes/database/database.incException thrown for merge queries that do not make semantic sense.
MergeQueryincludes/database/query.incGeneral class for an abstracted MERGE query operation.
NoFieldsExceptionincludes/database/database.incException thrown if an insert query doesn't specify insert or default fields.
Queryincludes/database/query.incBase class for query builders.
SelectQueryincludes/database/select.incQuery builder for SELECT statements.
SelectQueryExtenderincludes/database/select.incThe base extender class for Select queries.
SelectQuery_sqliteincludes/database/sqlite/select.incSQLite specific query builder for SELECT statements.
TruncateQueryincludes/database/query.incGeneral class for an abstracted TRUNCATE operation.
TruncateQuery_sqliteincludes/database/sqlite/query.incSQLite specific implementation of TruncateQuery.
UpdateQueryincludes/database/query.incGeneral class for an abstracted UPDATE operation.
UpdateQuery_sqliteincludes/database/sqlite/query.incSQLite specific implementation of UpdateQuery.


DatabaseStatementInterfaceincludes/database/database.incRepresents a prepared statement.
QueryAlterableInterfaceincludes/database/query.incInterface for a query that can be manipulated via an alter hook.
QueryConditionInterfaceincludes/database/query.incInterface for a conditional clause in a query.
QueryExtendableInterfaceincludes/database/select.incInterface for extendable query objects.
QueryPlaceholderInterfaceincludes/database/query.incInterface for a query that accepts placeholders.
SelectQueryInterfaceincludes/database/select.incInterface definition for a Select Query object.

Functions & methods

db_andincludes/database/database.incReturns a new DatabaseCondition, set to "AND" all conditions together.
db_closeincludes/database/database.incCloses the active database connection.
db_conditionincludes/database/database.incReturns a new DatabaseCondition, set to the specified conjunction.
db_deleteincludes/database/database.incReturns a new DeleteQuery object for the active database.
db_driverincludes/database/database.incRetrieves the name of the currently active database driver.
db_escape_fieldincludes/database/database.incRestricts a dynamic column or constraint name to safe characters.
db_escape_tableincludes/database/database.incRestricts a dynamic table name to safe characters.
db_insertincludes/database/database.incReturns a new InsertQuery object for the active database.
db_likeincludes/database/database.incEscapes characters that work as wildcard characters in a LIKE pattern.
db_mergeincludes/database/database.incReturns a new MergeQuery object for the active database.
db_next_idincludes/database/database.incRetrieves a unique id.
db_orincludes/database/database.incReturns a new DatabaseCondition, set to "OR" all conditions together.
db_queryincludes/database/database.incExecutes an arbitrary query string against the active database.
db_query_rangeincludes/database/database.incExecutes a query against the active database, restricted to a range.
db_query_temporaryincludes/database/database.incExecutes a query string and saves the result set to a temporary table.
db_selectincludes/database/database.incReturns a new SelectQuery object for the active database.
db_set_activeincludes/database/database.incSets a new active database.
db_transactionincludes/database/database.incReturns a new transaction object for the active database.
db_truncateincludes/database/database.incReturns a new TruncateQuery object for the active database.
db_updateincludes/database/database.incReturns a new UpdateQuery object for the active database.
db_xorincludes/database/database.incReturns a new DatabaseCondition, set to "XOR" all conditions together.


POSTGRESQL_NEXTID_LOCKincludes/database/pgsql/database.incThe name by which to obtain a lock for retrive the next insert id.


includes/database/, line 12
Core systems for the database layer.