census.module


// $Id$

/**
 * @file
  * Pulls data from a secondary census database on the same server.
 */


/**
 * Implements hook_menu()
 */

function census_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'census',
      'title' => t('Census'),
      'callback' => 'census_page',
      'access' => TRUE
    );
    $items[] = array(
      'path' => 'census/country',
      'title' => t('Census'),
      'callback' => 'census_country',
      'type' => MENU_CALLBACK,
      'access' => TRUE
    );
   }
  return $items;
}

/**
 * Default page
 */

function census_page() {
  $header = array(
    array('data' => t('Country'), 'field' => 'cid', 'sort' => 'ASC'),
     array('data' => t('Birth rate / 1000'), 'field' => 'births'),
    array('data' => t('Death rate / 1000'), 'field' => 'deaths'),   
        array('data' => t('Growth rate (%)'), 'field' => 'growth')
  );
  // grab the data from the external db
  db_set_active('external');
  $result = db_query("SELECT cid, country, births, deaths, growth FROM {country}". tablesort_sql($header));
  // switch back to Drupal before doing anything else!
  db_set_active('default');
  while ($data = db_fetch_object($result)) {
    $items[] = l($data->country, 'census/country/'. $data->cid);
    $rows[] = array(l($data->country, 'census/country/'. $data->cid), $data->births, $data->deaths, $data->growth .'%');
  }
  return theme('table', $header, $rows);
//  return theme('item_list', $items);
}

/**
 * Call based on country id
 */

function census_country($key) {
  // grab the data from the external db
  db_set_active('external');
  $data = db_fetch_object(db_query("SELECT * FROM {country} WHERE cid = %d", $key));
  // switch back to Drupal before doing anything else!
  db_set_active('default');
  drupal_set_title($data->country);
  $header = array();
  $temp = $data;
  unset($temp->cid);
  foreach ($temp as $key => $value) {
    $title = census_key($key);
    $rows[] = array($title, $value);
  }
  return theme('table', $header, $rows);
}

/**
 * Translate the table name to human name
 */

function census_key($key) {
  switch ($key) {
    case 'country':
      return t('Country');
    case 'births':
      return t('Live births per 1,000');
    case 'deaths':
      return t('Deaths per 1,000');
    case 'migration':
      return t('Net migration per 1,000');
    case 'increase':
      return t('Rate of natural increase');
    case 'growth':
      return t('Growth rate');
  }
}