Forum Moderators: coopster
Basically, something like this. Don't use an html form, use your script to output the form.
$errors='';
if (isset($_POST['some-input-variable'])) {
$errors = check_input_data();
if ($errors != '') {
$content ='<p style="color:red">There are some errors
in your form as follows, please make the
corrections and try again:</p><ul>' . $errors . '</ul>';
$content .= get_the_form();
}
else {
process_form(); // where you email, enter to DB, etc.
$content = 'Success'; // build success message here
}
}
else {
$content = get_the_form();
}
header("content-type:text/html");
echo $content;
Note the two bolded calls to get_the_form(), which compiles the form with or without input values. Something like
function get_the_form() {
$form = '
<form method="post" action="$myscript">
<p><label for="fname">First Name:</label>
<input type="text" name="fname" id="fname"
value="' . $_POST['fname'] . '"></p>
<!-- etc. -->
</form>
';
return $form;
}
So the first time through, there's nothing in post, blank values in form. On error, it will populate the values and re-output the form.
Do not put uncleansed values from input directly in your script as shown above, this is for example only. Cleanse them first.
You would do this in check_input_data(). In that function, if you find any errors, build a list, like
$err .= '<li>The email address is required.</li>';
So when it goes back to output the form, it fits nicely in between the <ul> and </ul>.
Then just put $stateList where it goes.
<p><label for="state">State:</label> $stateList </p>
function selectList($stateName); {
// You'd bulid a state array here, either from
// a static array or database - so you have $states
// already populated one way or another
$stateSelect = '<select name="' . $stateName .
' id="' . $stateName . '">'
<option value="">Select</option>';
foreach ($states as $st) {
$stateSelect .= '<option value="'.$st;
if ($_POST[$stateName]== $st) { $stateSelect .= ' selected'; }
// See previous warning about cleansing
$stateSelect .= '>' . $st . '</option>';
}
$stateSelect .= '</select>';
return $stateSelect;
}
Same of radios, checkboxes, etc. . . . think it through build it dynamically. In fact, a little head scratching can turn the above function into one that builds **any** kind of select list - depends on the context you're using it, what database tables are available, etc.