Recipe 9.11. Working with Multipage Forms


9.11.1. Problem

You want to use a form that displays more than one page and preserves data from one page to the next. For example, your form is for a survey that has too many questions to put them all on one page.

9.11.2. Solution

Use session tracking to store form information for each stage as well as a variable to keep track of what stage to display. Example 9-21 displays a two-page form and then the collected results.

Making a multipage form

<?php // Turn on sessions session_start(); // Figure out what stage to use if (($_SERVER['REQUEST_METHOD'] == 'GET') || (! isset($_POST['stage']))) {     $stage = 1; } else {     $stage = (int) $_POST['stage']; } // Save any submitted data if ($stage > 1) {     foreach ($_POST as $key => $value) {         $_SESSION[$key] = $value;     } } if ($stage == 1) { ?> <form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'> Name: <input type='text' name='name'/> <br/> Age:  <input type='text' name='age'/> </br/> <input type='hidden' name='stage' value='<?php echo $stage + 1 ?>'/> <input type='submit' value='Next'/> </form> <?php } else if ($stage == 2) { ?> <form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'> Favorite Color: <input type='text' name='color'/> <br/> Favorite Food:  <input type='text' name='food'/> </br/> <input type='hidden' name='stage' value='<?php echo $stage + 1 ?>'/> <input type='submit' value='Done'/> </form> <?php } else if ($stage == 3) { ?>     Hello <?php echo $_SESSION['name'] ?>.     You are <?php echo $_SESSION['age'] ?> years old.     Your favorite color is <?php echo $_SESSION['color'] ?>     and your favorite food is <?php echo $_SESSION['food'] ?>. <?php } ?>

9.11.3. Discussion

At the beginning of each stage in Example 9-21, all the submitted form variables are copied into $_SESSION. This makes them available on subsequent requests, including the code that runs in stage 3, which displays everything that's been saved.

PHP's sessions are perfect for this kind of task since all of the data in a session is stored on the server. This keeps each request small'no need to resubmit stuff that's been entered on a previous stage'and reduces the validation overhead. You only have to validate each piece of submitted data when it's submitted.

9.11.4. See Also

Recipe 11.1 for information about session handling.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net