Setup

Create a file sites/all/modules/own/custom/custom.info and write this in it:

1
2
3
4
name = Custom
description = Custom mdodule 
core = 7.x
package = Own

Create a file sites/all/modules/own/custom/custom.module and write opening php tag on the top

Note: Don’t start module name with a number and don’t add ending php tag (?>)!

Enable the module in /#overlay=admin/modules

Commenting

It’s a good practice to comment your modules so add this in you custom.module:

1
2
3
4
/**
 * @file
 * A simple module.
 */
@file Means that this comment describes the whole file.

Note: More about commenting conventions in here: API documentation and comment standards

Custom block

Now let’s create a block so we can see what’s happening with our module. Write this function in your custom.module:

1
2
3
4
5
6
7
/**
 * Implements hook_block_info.
 */
function custom_block_info() {
  $blocks['custom'] = array('info' => t('Custom block'));
  return $blocks;
}
hook_block_info() Tells Drupal that your module provides blocks.
$blocks[‘custom’] Drupal uses arrays extensively to store and pass information.
t() Translates your text to current/given language and adds extra security.

Note: block_info() is a hook. You can extend your module by implementing hooks. Hook is formatted like this: hook_block_info() and when you want to implement it replace the ‘hook’ with your module name: custom_block_info(). Another example of hook would be hook_node_insert. If your implement it with a function custom_node_insert, that function will run everytime a node is created. Read more: http://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7

If you want to use variables, pass them with placeholders so they get sanitized. Like this:

1
2
3
4
5
global $user;
$account = $user;
$blocks['custom'] = array(
  'info' => t('Custom block for @user', array('@user' => $account->name)),
);

Now you can see the block in /#overlay=admin/structure/block. Move it to Sidebar first and Save blocks.

Block content

Now let’s create some content for our block. Write this function in your custom.module:

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Implements hook_block_view.
 */
function custom_block_view($delta = '') {
  global $user;
  $account = $user;
  $block['content'] = t('Hello @user from IP @host',array(
    '@user' => format_username($account), 
    '@host' => $account->hostname
  ));
  return $block;
}
hook_block_view() Returns a view for your block.
$delta Unique identifier for the block.
format_username() Function to format a username (returns Anonymous if there is no $user->name).

Now you should see something like this in your sidebar:

Retrieving data

To retrieve data from database, we use Drupal Database API. Let’s fetch all node titles from node table:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Implements hook_block_view.
 */
function custom_block_view($delta = '') {
  global $user;
  $account = $user;
  $block['content'] = t('Hello @user from IP @host',array(
    '@user' => format_username($user), 
    '@host' => $account->hostname
  ));
  
  $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.
execute() Run the query.
theme() Creates themed output. HTML list in this case.

We iterate through the object with foreach and add titles to items[] array. Then we use theme() function to theme those titles to an item list and add that list to the block content.

Update, Delete and Insert

Update

You can update database items with db_update:

1
2
3
4
5
$update = db_update('node')
  ->fields(array(
    'title' => t('Updated by API')))
  ->condition('title','Test article 2','=')
  ->execute();

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

Delete

You can delete database items with db_delete:

1
2
3
$delete = db_delete('node')
  ->condition('title','Test article','=')
  ->execute();

Insert

You can insert database items with db_insert:

1
2
3
4
$insert = db_insert('node')
  ->fields(array(
    'title' => t('Test article 3')))
  ->execute();

Note: These were examples how to directly interact with database through Drupal Database API, but if you want to load, update and save nodes programmatically, these might be better: node_load(), node_save(), entity_load(), EntityFieldQuery.