Drupal's vendor-agnostic database abstraction layer provides a unified database query API that can query different underlying databases. It is built upon the PHP Data Objects (PDO) database API and inherits much of its syntax and semantics.
The Database API is designed to preserve the syntax and power of SQL as much as possible. It also:
- Supports multiple database servers
- Allows developers to leverage more complex functionality (i.e., transactions)
- Provides a structured interface to dynamically construct queries
- Enforces security checks
- Provides modules with an interface for modifying other queries in the system
The Database API may not always be the best option for interacting with data. API use in Drupal 8 is usually situational, e.g. using the Node API for Node CRUD operations, or the more generic Entity API for Entity for CRUD, the Configuration API for accessing configuration data, etc. We generally recommend directly querying the database as a last resort.
- Create a new database table for storing custom data
- Insert and retrieve data from a custom table or set of tables
- Query the watchdog table for log messages
Drupal's database abstraction layer did not change significantly between Drupal 7 and Drupal 8 and has been quite stable for some time. The primary difference in Drupal 8 is that access to the database should be done via a database connection service instead of the now deprecated
db_* functions. Query syntax and use of result sets remain similar.
We are still filling out our Drupal 8 library and this page will be updated with new tutorials as they are created.
- Entities topic
- In Drupal 8 the preferred method in most cases for storing and retrieving data is via the Entity API.
- An Overview of the Database Layer in Drupal 7
- High level overview of the database abstraction layer in Drupal 7. Good foundation for how the overall system works.
- Querying the Database with db_select() (Drupal 7)
- Adding a Table to the Database (Drupal 7)
- Querying the Database with Query Methods (Drupal 7)