A Complete Data Insertion Form in PHP Database

Example 8-28 combines the database topics covered so far in this chapter with the form-handling code from Chapter 7 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 8-28 relies on the FormHelper class defined in Example 7-29. Instead of repeating it in this example, the code assumes it has been saved into a file called FormHelper.php and then loads it with the require ‘FormHelper.php’ line at the top of the program.

Example 8-28. Program for inserting records into dishes


// Load the form helper class

require ‘FormHelper.php’;

// Connect to the database

try {

$db = new PDO(‘sqlite:/tmp/restaurant.db’);

} catch (PDOException $e) {

print “Can’t connect: ” . $e->getMessage();



// Set up exceptions on DB errors


// The main page logic:

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

// – If it’s not submitted, display


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

list($errors, $input) = validate_form();

if ($errors) {


} else {

// The submitted data is valid, so process it



} else {

// The form wasn’t submitted, so display



function show_form($errors = array()) {

// Set our own defaults: price is $5

$defaults = array(‘price’ => ‘5.00’);

// Set up the $form object with proper defaults

$form = new FormHelper($defaults);

// All the HTML and form display is in a separate file for clarity

include ‘insert-form.php’;


function validate_form() {

$input = array();

$errors = array();

// dish_name is required

$input[‘dish_name’] = trim($_POST[‘dish_name’] ?? ”);

if (! strlen($input[‘dish_name’])) {

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


// price must be a valid floating-point number and

// more than 0

$input[‘price’] = filter_input(INPUT_POST, ‘price’, FILTER_VALIDATE_FLOAT);

if ($input[‘price’] <= 0) {

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


// is_spicy defaults to ‘no’

$input[‘is_spicy’] = $_POST[‘is_spicy’] ?? ‘no’;

return array($errors, $input);


function process_form($input) {

// Access the global variable $db inside this function

global $db;

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

if ($input[‘is_spicy’] == ‘yes’) {

$is_spicy = 1;

} else {

$is_spicy = 0;


// Insert the new dish into the table

try {

$stmt = $db->prepare(‘INSERT INTO dishes (dish_name, price, is_spicy)

VALUES (?,?,?)’);

$stmt->execute(array($input[‘dish_name’], $input[‘price’],$is_spicy));

// Tell the user that we added a dish

print ‘Added ‘ . htmlentities($input[‘dish_name’]) . ‘ to the database.’;

} catch (PDOException $e) {

print “Couldn’t add your dish to the database.”;



Example 8-28 has the same basic structure as the form examples from Chapter 7: 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 ($_SERVER[‘ REQUEST_METHOD’ ] == ‘POST’). The new PDO() call establishes a data­base connection, and the next few lines check to make sure the connection succeeded and then set up exception mode for error handling.

The show_fom() function displays the form HTML defined in the insert-form.php file. This file is shown in Example 8-29.

Example 8-29. Form for inserting records into dishes

form method=”POST” action=”<?= $form->encode($_SERVER[‘PHP_SELF’]) ?>”>


<?php if ($errors) { ?>


<td>You need to correct the following errors:</td>


<?php foreach ($errors as $error) { ?>

<li><?= $form->encode($error) ?></li>

<?php } ?>


<?php }   ?>


<td>Dish Name:</td>

<td><?= $form->input(‘text’, [‘name’ => ‘dish_name’]) ?></td>




<td><?= $form->input(‘text’, [‘name’ => ‘price’]) ?></td>




<td><?= $form->input(‘checkbox’,[‘name’ => ‘is_spicy’,

 ‘value’ => ‘yes’]) ?> Yes</td>


<tr><td colspan=”2″ align=”center”>

<?= $form->input(‘submit’,[‘name’ => ‘save’,’value’ => ‘Order’]) ?>




Aside from connecting, all of the other 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, because the is_spicy column of the table holds a 1 in the rows of spicy dishes and a 0 in the rows of nonspicy dishes, the if() clause in process_form() assigns the appropriate value to the local variable $is_spicy based on what was submitted in $input[‘is_spicy’].

After that come the calls to prepare() and execute() that actually put the new infor­mation into the database. The INSERT statement has three placeholders that are filled by the variables $input[‘dish_name’], $input[‘price’], and $is_spicy. No value is necessary for the dish_id column because SQLite populates that automatically. Lastly, process_fom() prints a message telling the user that the dish was inserted. The htmlentitiesQ function protects against any HTML tags or JavaScript in the dish name. Because prepare() and execute() are inside a try block, if anything goes wrong, an alternate error message is printed.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *