Here is the problem. I have data validation and sanitation code in PHP and an HTML form. When there is some field left empty on the form, the validation code executes and prints a message. I thought I designed the form the way all the filled out fields retain their input data at that point. However, it proves to be inconsistent. For example, first and last name fields become empty, whereas the phone and street fields still have the data entered by a user before the validation occurred.
Here is the HTML:
<p>
<label for="firstname">FIRST NAME*:
</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname?>" />
</p>
<p>
<label for="lastname">LAST NAME*:
</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $lastname?>" />
</p>
<p>
<label for="phone">TELEPHONE NUMBER*:
</label>
<input type="text" name="phone" id="phone" value="<?php echo $phone?>" />
</p>
<p>
<label for="street">STREET ADDRESS*:
</label>
<input type="text" name="street" id="street" value="<?php echo $street?>" />
</p>
Here is the validation script:
if ($_POST['firstname'] != "") {
$_POST['firstname'] = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
if ($_POST['firstname'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
if ($_POST['lastname'] != "") {
$_POST['lastname'] = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
if ($_POST['lastname'] == "") {
$errors .= 'Please enter a valid last name.<br/><br/>';
}
} else {
$errors .= 'Please enter your last name.<br/>';
}
if ($_POST['phone'] != "") {
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
if ($_POST['phone'] == "") {
$errors .= 'Please enter a valid phone number.<br/><br/>';
}
} else {
$errors .= 'Please enter your phone number.<br/>';
}
if ($_POST['street'] != "") {
$street = filter_var($_POST['street'], FILTER_SANITIZE_STRING);
if ($_POST['street'] == "") {
$errors .= 'Please enter a valid street address.<br/><br/>';
}
} else {
$errors .= 'Please enter your street address.<br/>';
}
To me all the fields look the same. What could cause the inconsistency?
Thank you!