Insert queries

In order to get data into our custom database tables, we have an INSERT query builder that we can use. For this, and, the other types of queries, it is highly discouraged to use the db_query() approach because Drupal cannot ensure that it works across the different types of database engines. Instead, we can use the insert() method on the connection service and build our query using the Insert object that gets returned. So, let's see how we can add a record to our players table:

$database->insert('players');$fields = ['name' => 'Diego M', 'data' => serialize(['known for' => 'Hand of God'])];$id = $database->insert('players')  ->fields($fields)  ->execute();

The main thing about an insert query is the fields() method. It expects ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.