Database API overview
The Drupal 7 Database API provides a standard, vendor-agnostic abstraction layer for accessing database servers.
General concepts
The Drupal database layer is built on top of the PHP's PDO library. PDO provides a unified, object-oriented API for accessing different
Database configuration
The primary means of defining a database connection is via the $databases array in settings.php. As its name suggests, $databases allows
Static queries
Use static queries for simple SELECT statements that don't need to be altered at run-time.
Fetching into a custom class
Queries can be fetched into objects based on custom classes. For example, if we have a class named ExampleClass the following query will
Dynamic queries
Dynamic queries in Drupal 7 Database API.
Result sets
A Select query will always return a result set object of zero or more records. There are several ways to then retrieve data from that
Insert queries
Insert queries must always use a query builder object. Certain databases require special handling for LOB (Large OBject, such as TEXT in
Update queries
Update queries must always use a query builder object. Certain databases require special handling for LOB (Large OBject, such as TEXT on
Delete queries
Delete queries must always use a query builder object. They are started using the db_delete() function as follows:
Merge queries using db_merge
Merge queries are a special type of hybrid query. Although a syntax is defined for them in the SQL 2003 specification, virtually no
Writing database drivers
Coming soon, really! webchick insisted I post the documentation as it stands now, and this part isn't done yet. I'll get it added just as
Error handling
The Database API throws exceptions on error, which can be picked up by wrapping your database operations in try {} catch() {} blocks, as
Transactions
Drupal also supports transactions, including a transparent fallback for databases that do not support transactions. However, transactions
Chaining
There is a lot of talk about chaining database api functions together, for example:
Functions and operators
Drupal's database layer does not provide cross-database abstraction of SQL functions. For portability across supported database engines
SQL Views
The theory behind SQL Views, and the difference with the Views module.
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.