Module Development
Topic

Database Abstraction Layer for Drupal 7, 8, 9, 10, and 11

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 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.

Example tasks

  • 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

Confidence

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 the current version of Drupal 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.

Drupalize.Me resources

In Drupal the preferred method in most cases for storing and retrieving data is via the Entity API.

Categories
Module Development
Drupal 8, 9, 10, and 11
Drupal 7, 8, 9, 10, and 11
More information

Entities are the fundamental building blocks that make up any Drupal site. Having a good understanding of the Entity system is an important part of ensuring the data model of your Drupal site is set up properly.

Categories
Drupal 8, 9, 10, and 11
More information

Entity CRUD (Create, Read, Update, and Delete) operations are handled via the EntityTypeManager service.

In this tutorial we'll:

  • Learn how to use the EntityTypeManager service to perform basic CRUD operations with examples you can copy/paste
  • Access both property and field values of an entity
  • Update entities by setting new field values and then saving the object

By the end of this tutorial, you'll be able to understand Entity CRUD operations and be well on your way to becoming comfortable with accessing and manipulating entity values in code.

More information

Any Drupal module that provides custom database tables should implement hook_views_data() to describe the schema of those tables to Views. This hook is used to provide information to Views about the fields in a table, their human-readable names, and the types of data (string, integer, date, etc.) stored in each column. You can also tell Views how it should handle sorting, filtering, and formatting the data. Implementations of hook_views_data() can also be used to describe relationships between tables.

If you're creating a module that implements hook_schema() and adds new tables to the database it's a good idea to also add support for Views. Among other things, it'll allow administrators to create any user-facing displays of data from your table using Views. Then, they can be edited without having to write code. Once you've described your table to Views via hook_views_data() Views will be able to provide a way for administrators to construct queries against your data via the UI.

In this tutorial we'll:

  • Use hook_views_data() to expose a custom table defined in a Drupal module to Views.
  • Learn how to describe different types of data to Views.
  • Demonstrate the relationship between hook_views_data() and what a site administrator has access to in the Views UI.

By the end of this tutorial you should know how to describe custom database tables and their fields to the Views module.

Note: Use the service container to get a query object. After which queries work almost identically to Drupal 7.

$connection = \Drupal::database();
$query = $connection->select('node', 'n');
More information

In this excerpt from the Overview of Drupal 7, Angie Byron, talks about the Database API in Drupal 7. This was a round table discussion with other Lullabots on the line who ask and answer questions, in addition to Angie's presentation. This lays a good foundation for how the database system works in Drupal and sets you up for the hands-on tutorials that follow.

Additional resources

Database API documentation

More information

In this chapter we learn how to get data out of the database and display it. The example walks through writing a module that creates a page that displays how many nodes are published and unpublished for each content type in our site. We use the db_select() function to accomplish this.

More information

In this chapter we learn how to create a new database table. This example walks through creating a module that defines the the properties of our new table and also programatically creating that table. We learn about hook_schema() and hook_update_N() in our module's install file.

Trainers note: This video starts out with a module that implements hook_node_view() and stores data about views in the $_SESSION variable. It also states that we built this earlier in the series. However, that's not true. We did talk about hook_node_view() in https://drupalize.me/videos/event-driven-hook-system, but we never actually wrote the $_SESSION handling part. So, if you're following along and want the same sample code we start with make sure you download the code attached to this node.

More information

In this chapter we learn other ways to interact with our database beyond the simple db_select() query from the earlier video. This example walks through writing a module that that saves and displays data about how many times a user has visited a specific page. We learn about db_select(), db_insert(), db_update(), db_merge(), db_delete() and introduce the concept of "get and set" helper functions.

Guides

Not sure where to start? Our guides provide useful learning tracks for all skill levels.

Navigate guides

External resources

  • Database API (Drupal.org)
    • Detailed documentation on how to query a database using Drupal’s API.
  • Database abstraction layer (api.drupal.org)
    • Technical documentation for the database abstraction layer. Use this if you just need a quick reminder about how a particular feature works.