Sticky Forms

A sticky form is a form that remembers the values you typoed in the input fields. With a sticky form, the input data can be saved so that when the form is redisplayed, the data is still there.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$errors = array();
if (isset($_POST['submit'])) {
	validate_form();
	if (count($errors) !=0) {
		display_errors();
		display_form();
	}
	else {
		display_errors();
		echo "processing form...<br />";
		process_form();
	}
}
else {
	display_form();  // display form for the first time
}

function validate_form() {
	global $errors;
	if ($_POST['name'] == "") {
		$errors['name']="<font color='red'>Please enter your name.</font>";
	}
	if ($_POST['phone'] == "") {
		$errors['phone']="<font color='red'>Please enter your phone.</font>";
	}
}

function display_form() {
echo <<<HTML
<form action = "$_SERVER[SCRIPT_NAME]" method="post">
Enter your name
<input type="text" name="name" value="$_POST[name]" /><br />
Enter your phone
<input type="text" name="phone" value="$_POST[phone]" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
HTML;
}

function process_form() {
	echo <<<EOF
	Your name is: $_POST[name]<br />
	Your phone is: $_POST[phone]
EOF;
}

function display_errors() {
	global $errors;
	foreach ($errors as $values) {
		echo $values, "<br />";
	}

}
?>
</p>
</body>
</html>

View the effect


Forms | Introduction | Creating a Form | Superglobals | Processing Form Input | Required Fields | Numbers | Drop-Down Menus | Radio Buttons | Checkboxes | Periods in Their Names | Preventing Cross-Site Scripting | Stripping out Slashes | Redirecting the User | Server Information | Determining Browser Type | Sticky Forms
© 2008: Hann So
email: hso@voyager.deanza.edu