php form display function

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I hope I can state this clearly enough.

I am redoing some of my html(php) forms.  I'm trying to break things
into three functions on a self processing php page:
   1) show the form (and populate fields if there were errors)
   2) validate form data
   3) process form data

2 and 3 are no problem, but 1 is.  The page with the form displayed
should validate as html 4.01 strict (actually all iterations of the page
need to validate).  The actual page is a mix of php and html (popping in
and out of php w/ '<?PHP' and  '?>' as needed,  so that I can see what
the page layout will be.  To validate I have been  serving page.php
saving it as page.html and validating that.  I'm sure there is a better
way to do this.

To keep the code logic and  markup 'separate' and easier to read, I have
been using include files of valid html (i.e. a div containing the
form,with my pop-in's of php, or a div containing the 'thank you, we'll
get back to you'). like this:

if (array_key_exists('_submit_check',$_POST)) {
      if ($form_errors = validate_form()) {
         //the form has errors or was submitted by another source
      } else {
    // The submitted data is valid, so process it
} else { // The form wasn't submitted, so display

Is there a good way to show the form, any errors and re-populating all
the form fields?  I thought about using session variables (seeding the
form and storing values until all errors have been resolved), but am not
sure that's the way to go.

Re: php form display function

Quoted text here. Click to load it

I would do two things
1. Write the form with a conditional statement next to each input (if
$error then display error message)
2. Write each element like <input type="text" id="fname" value="<?=
$_POST['fname'] />. The first time somebody comes to the form there
will be nothing in POST, so the form will be blank. Subsequent
attempts will carry forward the data they've already entered.

Re: php form display function

Kevin Audleman wrote:
Quoted text here. Click to load it

I had thought about putting the errors in an associative array using the
field name as the index, and then doing something like:

<?php array_key_exists('fname', $error_array) ? ?>
     <input name="fname" type="text" value ="<?php echo
     <?php : ?>
     <input name="fname" type="text" value ="<?php echo>

Site Timeline