[Drupal-8] How to Handle Select, Update, Delete Database Operations in Drupal 8?

| | 1 min read

In Drupal 8, the usage of database operations such as select, update and delete are slightly changed from Drupal 7. The db_query() is deprecated in Drupal 8. To fetch a field we can use :

$query = \Drupal::database()->query('SELECT myfield from my_table where
  field1 = :value1 AND field2 = :value2', array(
    ':value1' => $condition1,
    ':value2' => $condition2,
  )
);
$data = $query->fetchField();

Now we can checkout the select, update, and delete operations in Drupal 8. For a field selection use,

$query = \Drupal::database()->select('table_name', 'alias')
  ->fields('alias', ['field1', field2])
  ->condition('field3', $condition);
$results = $query->execute();
while ($content = $results->fetchAssoc()) {
  // Operations using $content.
}

For a single field selection we can use $last_paper_id = $last_paper->fetchField();

For update query execution in Drupal 8, we can use,

$table = 'table_name';
\Drupal::database()->update($table)
  ->fields(array('field1' => $value1, 'field2' => $value2))
  ->condition('field3', $condition1)
  ->condition('field4', $condition2)
  ->execute();

For content deletion,

$query = \Drupal::database()->delete('table_name');
  $query->condition('field1', $condition1);
  $query->condition('field2', $condition2);
  $query->execute();

Now checkout other database statements in Drupal 8 from this link!