O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

<?php // Load PEAR DB require 'DB.php'; // Load the form helper functions require 'formhelpers.php'; // Connect to the database $db = DB::connect('mysql://hunter:w)mp3s@db.example.com/restaurant'); if (DB::isError($db)) { die ("Can't connect: " . $db->getMessage( )); } // Set up automatic error handling $db->setErrorHandling(PEAR_ERROR_DIE); // 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( )) { show_form($form_errors); } else { // The submitted data is valid, so process it process_form( ); } } else { // The form ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required