What is the best way to handle form data for a two part form? I've found a couple of different approaches, but I would like to find out the best practice to handling this type of form.

Here are a couple of methods I've found. First option, use hidden inputs on the second part of the form to retain the values. Second option, store the info in the database temporarily and retrieve when needed to complete the form. Third option, but have found less information on this, store variable in a session array and use as needed.

Here is a basic outline on how I've built the page so far. The page posts to itself.

Form 1
Is the form that displays by default. It has about 15 fields for user input. Once posted, calls an external php file to validation. If everything passes validation, then a variable is set. This variable lets the page know to hide Form 1 and display Form 2.

This is the basic code, but seems fairly rudimentary.

if (checkFields() != TRUE) {
	return FALSE;
}
else {
	$step = 2;
}

A switch statement exists to check which step the user is on and displays the appropriate form depending on what the $step variable is set as.

Form 2
This has about 5 fields and also calls an external php to handle validation. If it passes validation everything is submitted to the database.

if (checkFields() != TRUE) {
	$step = 2;
}
else {
	commence with the INSERT
}

Also, should I revalidate the data from Form 1 after it passed the initial validation?

Thanks for any insight.

    Sessions are your friend. PHP automatically handles a lot of session-related stuff so you don't have to.

    The basic idea with sessions is that you can store a bunch of information in a PHP variable and have it available when the user navigates to another page.

    form1.php

    if (checkFields() != TRUE) {
        return FALSE;
    } else {
      // not sure what $step does, so I just put some code in here which
      // would store the $_POST data in session and redirect to form2.php
      session_start(); // call this function to 'turn sessions on'
      $_SESSION['form_one_post_data'] = $_POST; // store your form POST data to session
      header('location: form2.php'); // redirect to form.php
      exit(); // halt code execution
    } 
    

    Then in your second form, you can retrieve the vars from session. Users can be sneaky sometimes so if you want to be absolutely certain that the user has filled out form 1, you may need to re-validate them.
    form1.php

    session_start(); // start session handling
    $form_1_post = $_SESSION['form_one_post_data']; // retrieve the POST data submitted in form 1
    

      Thanks guys. This is exactly what I was looking for. Sessions seem to be the easier method. I just wasn't sure what exactly was the favored approach.

        As a side note. By going to SESSION variables I was able to remove the nonsense of the $step variable I was using to track where the user is in the process. Thanks Again.

          Write a Reply...