I have a simple xhtml form with textboxes asking the user for their name, id, address etc. I have to use php to validate the data. For example in the ID field exactly 6 numerical values are allowed, if thats not the case, it shows an error to the user asking them to fix it. What i want do is, when the user clicks submit with the incorrect data, i want to keep the data in the field when the error shows up. I am currently doing that by:-
<td><label for="customerid">*Customer ID: </label></td>
<td><input type="text" value="
<?php if(($_POST['customerid'] != $id) || ($_POST["customerfname"] != $fname)
|| ($_POST["customerlname"] != $lname)){echo $_POST['customerid'];} ?>"
id="customerid" name="customerid"/>
I have just been modyifying that statement for all textboxes but as you can imagine it will get a little complicated if i have to do that for 10 boxes. i was wondering if it was an easier way to do this.
bold UPDATED
<td> <select name="state" id="state" value="<?php echo (isset($_POST["state"]) ? : ''); ?>">
<option value="--">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="QLD">QLD</option>
<option value="SA">SA</option>
</select>
</td>
Something like this?
<input type="text" name="customerid" value="<?php echo (isset($_POST['customerid']) ? $_POST['customerid'] : ''); ?>">
Update - run your checks before the form is re-generated
<?php
if(($_POST['customerid'] != $id) || ($_POST["customerfname"] != $fname) || ($_POST["customerlname"] != $lname))
{
// do nothing
}
else
{
$_POST['customerid'] = '';
}
?>
<input type="text" name="customerid" value="<?php echo (isset($_POST['customerid']) ? $_POST['customerid'] : ''); ?>">
A few things you can do here either separately, or in some combination:
$_SESSION
array and just echo them into the field if they are set. ex <input type='text' value='<?php echo $_SESSION['myVal'] || '';?>'></input>
what are those statements?
$_POST['customerid'] != $id
you can make $fields array to store labels an $errors array to place errors in and then just
<?php $fields = array ('customerId' => '*CustomerID'); ?>
<?php // validation ?>
<?php foreach($fields as $name => $label): ?>
<td><label for="<?php echo $name ?>"><?php echo $label?>: </label></td>
<td>
<input type="text" value="" id="<?php echo $name ?>" name="<?php echo $name ?>">
<?php if(isset($errors[$name])): ?>
<?php echo $errors[$name] ?>
<?php endif; ?>
</td>
<?php endforeach; ?>
You could also add html validation to the form to stop the user from submitting empty form by adding "required" attribute to inputs (<input required ... >
) or the "pattern" attribute