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 an array of key/value pairs, where the keys are the column names and the values are the data that needs to be added to the respective columns. Alternatively, the first argument can be an array of the column names and the second an array of the values in the same order as the column names from the first array.

We can also run an INSERT query with multiple sets of values (records):

$values = [
['name' => 'Novak D.', 'data' => serialize(['sport' => 'tennis'])],
['name' => 'Micheal P.', 'data' => serialize(['sport' => 'swimming'])]
];
$fields = ['name', 'data'];
$query = $database->insert('players')
->fields($fields);
foreach ($values as $value) {
$query->values($value);
}
$result = $query->execute();

In this example, the fields() method receives only an array of column names that need to be inserted, and we use values() method calls to add the individual values.

The execute() method typically returns the ID (primary key) of the last record to be inserted. This is handy, especially if you insert only one record. However, for multiple inserts, it can also be misleading. So, do experiment for yourself with different use cases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset