How to Perform Insert, Update, Delete, and Select Database Queries in Your Drupal Module

16 / Aug / 2023 by Rajveer Singh 0 comments

If you’re building a Drupal 10 website, you’ll probably need to work with a database at some point. Whether you’re retrieving data from the database or making changes, you’ll need to use SQL queries. In this blog post, we’ll cover the basics of four common database queries in Drupal 10: insert, update, delete, and select.

An insert query adds new data to a database table. Here’s an example of an insert query in Drupal 10:

$query = \Drupal::database()->insert('ttn_mysql_table');
$query->fields([ 'name' => 'Rajveer', 'age' => 30,]);
$query->execute();


Update Query

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

$query = \Drupal::database()->update('ttn_mysql_table');
$query->fields([
'age' => 31,
]);
$query->condition('name', 'Rajveer');
$query->execute();

Delete Query

A delete query removes data from a database table. Here’s an example of a delete query in Drupal 10:

$query = \Drupal::database()->delete('ttn_mysql_table');
$query->condition('age', 30);
$query->execute();

Select Query

A select query retrieves data from a database table. Here’s an example of a select query in Drupal 10:

$query = \Drupal::database()->select('ttn_mysql_table', 't');
$query->fields('t', ['id', 'name']);
$result = $query->execute();

foreach ($result as $row) {
$id = $row->id;
$name = $row->name;
// Do something with the results.
}

Feed your curiosity – read more of our insightful blogs.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *