Pages

Thursday, February 17, 2011

Drupal Module - Inset Data

This module provide implementations for insert data to database
0. structure of table data
mysql>> CREATE TABLE data
     >> (id INT NOT NULL AUTO_INCREMENT KEY,
     >> name CHAR(50),
     >> city CHAR(50));

1. data.info
name = Module Data Insert
description = Module for inserting data to database
package = Data Access
version = 1.0
core = 7.x

2. data.module
<?php
/**
 * Implements hook_menu()
 */
function data_menu(){
    $items = array()

    $items['data/main'] = array(
        'title' => 'Insert Data',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('data_insert_form'),
        'access callback' => TRUE,
    );

    return $items;
}

/**
 * Form to get the data input
 */
function data_insert_form( $form, &$form_state){
    $form['name'] = array(
         '#type' => 'textfield',
         '#title' => t('Name'),
    ),
    $form['city'] = array(
         '#type' => 'textfield',
         '#title' => t('City'),
    ),
    $form['submit'] = array(
        '#type' => 'textfield',
        '#value' => t('Insert To Database'),
    );

    return $form;
}


/**
 * Handling submit form
 */
function data_insert_form_submit($form, &$form_state){

    // get the value from field submitting
    $entry = array(
        'name' => $form_state['values']['name'],
        'city' => $form_state['values']['city'],
    );

    // insert to database
    $return = db_insert('data')->fields($entry)->execute();

    if($return){
        drupal_set_message("Your data has been insert successfully");
    }else{
        drupal_set_message("Oops. Unable to save");
    }
}

No comments:

Post a Comment