How To Inserting, Retrieving, Updating and Deleting in database through custom module in Drupal 7 ?

  0 comments Share with:

In previous blog Create block through Custom Module in Drupal 7 learned about creating block through custom module. Now will learn Retrieving, Insertion, Deletion, and Updation through custom module.

Note :

You can see the basic setup for module at this blog Create block through Custom Module in Drupal 7 or create-custom-module

Retrieving Data

To retrieve the data from database we use Drupal Database API Ex: Retrieving title from node table

function custom_module_block_view($delta = '') { $result = db_select('node','a') ->fields('a', array('title')) ->execute(); foreach($result as $node) { $items[] = array( 'data' => t($node->title) ); } $block['content'] = theme('item_list', array( 'items' => $items )); return $block; }


db_select($table, $alias) Returns a SelectQuery object.

$table Target table for the query.

$alias Alias for the table.

fields() Fields to SELECT from $table

theme() Creates themed output.

execute() Run the query.


For Updation we use this

$update = db_update('node') ->fields(array( 'title' => t('Updated by API'))) ->condition('title','Test blog 2','=') ->execute();

condition() Condition clause to restrict fetched rows by a condition. (Notice that the operator goes as last argument!)


$delete = db_delete('node') ->condition('title','Test blog','=') ->execute();


$insert = db_insert('node') ->fields(array( 'title' => t('Test blog 3'))) ->execute();

Add new comment