Example 5: Load Table Data from the Database

When loading the data for a table, it is quite likely your module will be loading data from the database for display. This example shows the appropriate place to insert the code and a simple method for filling your data arrays with the loaded information. This code loads the information for the table from example 1 from a database table.

Example: view page

Code:

<?php
function tapirtest_menu($may_cache) {
  if (
$may_cache) {
   
$items[] = array(
     
'path' => 'tapirtest/example_5',
     
'title' => t('Example 5: Load Table Data from the Database'),
     
'callback' => 'tapirtest_example_5',
     
'access' => user_access('access content'),
     
'type' => MENU_CALLBACK,
    );
  }
  return
$items;
}

function

tapirtest_example_5() {
 
$output = '<p>'. tapir_get_table('tapirtest_example_table_5', $null) .'</p>';
  return
$output;
}

function

tapirtest_example_table_5 ($op) {
  switch (
$op) {
    case
'fields':
     
$fields[] = array('name' => 'song', 'title' => t('Song'), 'weight' => 0, 'enabled' => TRUE);
     
$fields[] = array('name' => 'artist', 'title' => t('Artist'), 'weight' => 1,
                      
'enabled' => TRUE);
     
$fields[] = array('name' => 'album', 'title' => t('Album'), 'weight' => 2,
                      
'enabled' => TRUE);
      return
$fields;
    case
'data':
     
$result = db_query("SELECT song, artist, album FROM {tapirtest_example_5}");
      while (
$row = db_fetch_object($result)) {
       
$data['song'][] = $row->song;
       
$data['artist'][] = $row->artist;
       
$data['album'][] = $row->album;
      }
      return
$data;
  }
}
?>