Previous Section  < Day Day Up >  Next Section

7.7 A Complete Data Insertion Form

Example 7-30 combines the database topics covered so far in this chapter with the form-handling code from Chapter 6 to build a complete program that displays a form, validates the submitted data, and then saves the data into a database table. The form displays input elements for the name of a dish, the price of a dish, and whether the dish is spicy. The information is inserted into the dishes table.

The code in Example 7-30 relies on the form helper functions defined in Example 6-29. Instead of repeating them in this example, the code assumes they have been saved into a file called formhelpers.php and then loads them with the require 'formhelpers.php' line at the top of the program.

Example 7-30. Form for inserting records into dishes

// Load PEAR DB

require 'DB.php';

// Load the form helper functions

require 'formhelpers.php';

// Connect to the database

$db = DB::connect('mysql://hunter:w)');

if (DB::isError($db)) { die ("Can't connect: " . $db->getMessage( )); }

// Set up automatic error handling


// The main page logic:

// - If the form is submitted, validate and then process or redisplay

// - If it's not submitted, display

if ($_POST['_submit_check']) {

    // If validate_form( ) returns errors, pass them to show_form( )

    if ($form_errors = validate_form( )) {


    } else {

        // The submitted data is valid, so process it

        process_form( );


} else {

    // The form wasn't submitted, so display

    show_form( );


function show_form($errors = '') {

    // If the form is submitted, get defaults from submitted parameters

    if ($_POST['_submit_check']) {

        $defaults = $_POST;

    } else {

        // Otherwise, set our own defaults: price is $5

        $defaults = array('price' => '5.00');



    // If errors were passed in, put them in $error_text (with HTML markup)

    if ($errors) {

        $error_text = '<tr><td>You need to correct the following errors:';

        $error_text .= '</td><td><ul><li>';

        $error_text .= implode('</li><li>',$errors);

        $error_text .= '</li></ul></td></tr>';

    } else {

        // No errors? Then $error_text is blank

        $error_text = '';


    // Jump out of PHP mode to make displaying all the HTML tags easier


<form method="POST" action="<?php print $_SERVER['PHP_SELF']; ?>">


<?php print $error_text ?>

<tr><td>Dish Name:</td>

<td><?php input_text('dish_name', $defaults); ?></td></tr>


<td><?php input_text('price', $defaults); ?></td></tr>


<td><?php input_radiocheck('checkbox','is_spicy', $defaults, 'yes'); ?>


<tr><td colspan="2" align="center"><?php input_submit('save','Order'); ?>



<input type="hidden" name="_submit_check" value="1"/>



      } // The end of show_form( )

function validate_form( ) {

    $errors = array( );

    // dish_name is required

    if (! strlen(trim($_POST['dish_name']))) {

        $errors[  ] = 'Please enter the name of the dish.';


    // price must be a valid floating point number and 

    // more than 0

    if (floatval($_POST['price']) <= 0) {

        $errors[  ] = 'Please enter a valid price.';


    return $errors;


function process_form( ) {

    // Access the global variable $db inside this function

    global $db;

    // Get a unique ID for this dish

    $dish_id = $db->nextID('dishes');

    // Set the value of $is_spicy based on the checkbox

    if ($_POST['is_spicy'] =  = 'yes') {

        $is_spicy = 1;

    } else {

        $is_spicy = 0;


    // Insert the new dish into the table

    $db->query('INSERT INTO dishes (dish_id, dish_name, price, is_spicy)

                VALUES (?,?,?,?)',

               array($dish_id, $_POST['dish_name'], $_POST['price'],


    // Tell the user that we added a dish.

    print 'Added ' . htmlentities($_POST['dish_name']) . 

          ' to the database.';



Example 7-30 has the same basic structure as the form examples from Chapter 6: functions for displaying, validating, and processing the form with some global logic that determines which function to call. The two new pieces are the global code that sets up the database connection and the database-related activities in process_form( ).

The database setup code comes after the require statements and before the if($_POST['_submit_check']). The DB::connect( ) function establishes a database connection, and the next three lines check whether the connection succeeded and turn on automatic error handling for the rest of the program.

All of the interaction with the database is in the process_form( ) function. First, the global $db line lets you refer to the database connection variable inside the function as $db instead of the clumsier $GLOBALS['db']. Then, nextId( ) gets a unique integer ID for the new dish about to be saved. The is_spicy column of the table holds a 1 in the rows of spicy dishes and a 0 in nonspicy dishes, so the if( ) clause in process_form( ) assigns the appropriate value to the local variable $is_spicy based on what was submitted in $_POST['is_spicy'].

After that comes the call to query( ) that actually puts the new information into the database. The INSERT statement has four placeholders that are filled by the variables $dish_id, $_POST['dish_name'], $_POST['price'], and $is_spicy. Last, process_form( ) prints a message telling the user that the dish was inserted. The htmlentities( ) function protects against any HTML tags or JavaScript in the dish name.

    Previous Section  < Day Day Up >  Next Section