Database API

Views:4

Delete a Record

Deletes a record from a specific table
Delete a Record
              

/**
* Deletes a record from a custom table.
*/
function my_module_delete_data() {
    \Drupal::database()->delete('custom_table')
        ->condition('id', 10, '=')
        ->execute();
}
 


Insert Data into a Table

Inserts a new record into a table
Insert Data into a Table
              

/**
* Inserts a record into a custom table.
*/
function my_module_insert_data() {
    \Drupal::database()->insert('custom_table')
        ->fields([
            'name' => 'Sample Name',
            'status' => 1,
        ])
        ->execute();
}
 


Simple Select Query

Basic query to fetch results from a specific table
Simple Select Query
              

/**
* Fetches data from a custom table.
*/
function my_module_get_data() {
    $query = \Drupal::database()->select('custom_table', 'ct');
    $query->fields('ct', ['id', 'name', 'status']);

    $result = $query->execute()->fetchAll();

    return $result;
}
 


Update Data in a Table

Updates an existing record in a table
Update Data in a Table
              

/**
* Updates data in a custom table.
*/
function my_module_update_data() {
    \Drupal::database()->update('custom_table')
        ->fields([
            'status' => 0,
        ])
        ->condition('id', 5, '=')
        ->execute();
}