Redisplaying a Form After PHP Validation Fails






Redisplaying a Form After PHP Validation Fails

While you intend for JavaScript to catch errors up front, before the user has navigated away from the page through the form submission, there will be times when PHP catches an error. When this happens, an informative error message displays and the form is redisplayed that had a validation problem. When redisplaying the form, it's a much smoother user experience if the data the user submitted is pre-populated in the form. There's nothing worse than filling out a page-long form only to find out there's a missing checkbox, meaning you have to start over.

We'll modify our previous example to check whether a username is already present in the users table, as shown in Figure.

Displaying an error from PHP and redisplaying the form with submitted values

<html>
<head>
<title>Sample Form</title>
<script type="text/javascript" src="source.js"></script>
<script type="text/javascript">
function check_valid(form) {
var error = "";
error += verify_username(form.username.value);
error += verify_password(form.password.value);
error += verify_phone(form.phone.value);
error += verify_email(form.email.value);
if (error != "") {
alert(error);
return false;
}
return true;
}
</script>
</head>
<body>
<?php
// Check for form post submit
if ($_POST["submit"]){
require_once('db_login.php');
require_once('DB.php');
$connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");
if (DB::isError($connection)){
die ("Could not connect to the database: <br />". DB::errorMessage($connection));
}
// Remember to use htmlentities to prevent cross-site scripting vulerablities
$username = htmlentities($_POST["username"]);
$password = htmlentities($_POST["password"]);
$email = htmlentities($_POST["email"]);
$phone = htmlentities($_POST["phone"]);
$error = "";
if ($username == ""){
$error .= "Username must not be null.<br />";
}
if ($password == ""){
$error .= "Password must not be null.<br />";
}
if ($email == ""){
$error .= "Email must not be null.<br />";
}
if ($phone == ""){
$error .= "Phone must not be null.<br />";
}
// Query the posts with catagories and user information
$query = "SELECT * FROM `users` WHERE `username`='$username'";
// Execute the database query
$result = $connection->query($query);
if (DB::isError($result)){
die("Could not query the database: <br />".$query." ".DB::errorMessage($result));
}
$user_count = $result->numRows();
if ($user_count > 0) {
$error .= "Error: Username $username is taken already. Please select another.<br />";
}
if ($error){
echo $error;
}
else {
echo "User created successfully.";
exit;
}
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST"
onsubmit="return check_valid(this);" id="test1" name="test1">
<table>
<tr>
<td width="30%" align="right">Username:</td>
<td><input type="text" name="username" value="<?php echo
htmlspecialchars(stripslashes($username)); ?>" /></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="password" value="<?php echo
htmlspecialchars(stripslashes($password)); ?>" /></td>
</tr>
<tr>
<td align="right">Phone:</td>
<td><input type="phone" name="phone" value="<?php echo
htmlspecialchars(stripslashes($phone)); ?>" /></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input type="email" name="email" value="<?php echo
htmlspecialchars(stripslashes($email)); ?>" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>

If a user enters invalid data, as shown in Figure, she'll get the response shown in Figure. If the data is correct, she'll see the response in Figure.

The form before submission with a conflicting username


After form submission, the error displays and the form repopulates


A successful submission




 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows