Remember form data on error

Got an email with this question:

What I am seeking is an
equally easy PHP inclusion that retains drop down and radio button entries when
a form has an error on submission.

…..Meaning, If I complete one of my long PHP forms, and they fail to enter content in
the required fields, an error code shows as developed but all the drop down
selections go back to default and all radio buttons selections are deleted.

Short answer, cant be done as an include file to an existing form. 

If you have coded your form like this:

<input type="text" name="first_name" 

Then you will need to continue doing it for drop down select boxes and radio boxes like this:

<select name="foo">
  <option value="1"<?=($_POST['foo']==1)?" selected":"";?>>Option 1</option>
  <option value="2"<?=($_POST['foo']==2)?" selected":"";?>>Option 2</option>
  <option value="3"<?=($_POST['foo']==3)?" selected":"";?>>Option 3</option>

 or instead of coding each option value manually, you can use an array like so:

// specify drop down field values in array:
$drop_down_fields = array(
  "value1"=>"Value 1",
  "value2"=>"Value 2",
  "value3"=>"Value 3",
  "value4"=>"Value 4",
// name your drop down select box:
$drop_down_name = "my_drop_down_box";
<select name="<?=$drop_down_name;?>">
<option value="">Please select an option</option>
<?php foreach($drop_down_fields as $key=>$val){ ?>
  <option value="<?=$key;?>"
<?=($_REQUEST[$drop_down_name]==$key)?" selected":"";?>
<?php } ?>

 and to make checkboxes remember their selection after submitting a form do something like this:

<input type=”checkbox”



 or an idea solution is to specify all your form elements as an object or array first
before you start to worry about how to display them on the screen. Once
you have the form elements defined in a php array you can do anything
with them, an example of this is here:

Leave a Reply

Your email address will not be published.