Skip to main content

Database Update examples

DrupalVIP Support

An update query changes data in an existing database table. 
Here’s an example of an update query in Drupal 10

Update queries must always use a query builder object. 
Certain databases require special handling for LOB (Large OBject, such as TEXT on MySQL) and BLOB (Binary Large OBject) fields, so a layer of abstraction is required to allow individual database drivers to implement whatever special handling they require.

$query = \Drupal::database()->update('ttn_mysql_table');
$query->fields([
'age' => 31,
]);
$query->condition('name', 'Rajveer');
$query->execute();
$num_updated = $connection->update('mytable')
  ->fields([
    'field1' => 5,
    'field2' => 1,
  ])
  ->condition('created', \Drupal::time()->getRequestTime() - 3600, '>=')
  ->execute();
$query = $connection->update('mytable')
  ->condition('module', 'my_module')
  ->where(
    'SUBSTR(delta, 1, 14) <> :module_key',
    [':module_key' => 'my_module-key_']
  )
  ->expression('delta', "REPLACE(delta, :old_value, :new_value)", [
    ':old_value' => 'my_module-other_',
    ':new_value' => 'my_module-thing_',
  ])
  ->execute();

function  deprecated:  db_update

in drupal:8.0.0 and is removed from drupal:9.0.0. 
Instead, get a database connection injected into your service from the container and call update() on it. 
For example, $injected_database->update($table, $options);