Forms are part of virtually any web application today. They are the main method to receive input from people using the application. They range in size from one-field opt-in forms where you only enter your email address, to very long forms with tens or even hundreds of fields.
To make long forms user-friendlier, it is a good idea to span the form on multiple pages. This can make it easier to follow for the user, and we can also split the data in separate sections, based on the scope (for example separate personal customer information from payment data in a shopping cart checkout form).
One of the challenges that arise from splitting the form over multiple pages is passing the data from one page to another, as at the final point of the form, we have all the needed data ready for processing. We are going to look at two methods to do this: session variables and hidden input fields.
What are sessions anyway?
A HTML session is a collection of variables that keeps its state as the user navigates the pages of a certain site. It will only be available to that domain that created it, and will be deleted soon after the user left the site or closed his browser.
So, the session has a semi-permanent nature, and it can be used to pass variables along different pages on which the visitor lands during a visit to the site.
Multi-page form using sessions
In our example, we are going to create a three pages form, resembling a membership signup and payment form. The first page will ask for customer's name and address, on the second page there is the choice for membership type, and on the third and final page, payment data must be entered. Final step is saving the data in MySQL.
The first file we are going to create (step 1 of the form) will contain just a simple form with two fields.
<form method="post" action="form2.php">
<input type="text" name="name">
<input type="text" name="email_address">
<input type="submit" value="Go To Step 2">
</form>Ok, so nothing more than 2 input fields and a submit button to take us to step 2. In the following page, apart from the HTML form to gather membership data, we are going to need code to store the submitted data from step 1 in the session.
<?php
//let's start the session
session_start();
//now, let's register our session variables
session_register('name');
session_register('email_address');
//finally, let's store our posted values in the session variables
$_SESSION['name'] = $_POST['name'];
$_SESSION['email_address'] = $_POST['email_address'];
?><form method="post" action="form3.php"> <input type="radio" name="membership_type" value="Free"> <input type="radio" name="membership_type" value="Normal"> <input type="radio" name="membership_type" value="Deluxe"> <input type="checkbox" name="terms_and_conditions"> <input type="submit" value="Go To Step 3"> </form>
On to step 3, we must again create new session variables, assign values received by post, and create the final part of the form.
<?php
//let's start the session
session_start();
//now, let's register our session variables
session_register('membership_type');
session_register('terms_and_conditions');
//finally, let's store our posted values in the session variables
$_SESSION['membership_type'] = $_POST['membership_type'];
$_SESSION['terms_and_conditions'] = $_POST['terms_and_conditions'];
?><form method="post" action="form_process.php"> <input type="text" name="name_on_card"> <input type="text" name="credit_card_number"> <input type="text" name="credit_card_expiration_date"> <input type="submit" value="Finish"> </form>
Now that we created step 3 of the form, what's left is the final processing script that inserts the data in the MySQL database.
<?php //let's start our session, so we have access to stored data session_start(); //let's create the query $insert_query = 'insert into subscriptions ( name, email_address, membership_type terms_and_conditions, name_on_card, credit_card_number, credit_card_expiration_date ) values ( " . $_SESSION['name'] . ", " . $_SESSION['email_address'] . ", " . $_SESSION['membership_type'] . ", " . $_SESSION['terms_and_conditions'] . ", " . $_POST['name_on_card'] . ", " . $_POST['credit_card_number'] . ", " . $_POST['credit_card_expiration_date'] . " ); //let's run the query mysql_query($insert_query); ?>
And we are done. Please note that in the final query, we are using data from the $_SESSION array, and also data from the $_POST array, that was posted from the last step of the form.
No related posts.




{ 56 comments… read them below or add one }
Next Comments →
Thanks… thats a really quick n easy solution
I am getting an error on line 16 in the last part of the script. Please help
<code>
[code]</p>
<p><?php
//let's start our session, so we have access to stored data
session_start();
//let's create the query
$insert_query = 'insert into subscriptions (
name,
email_address,
membership_type
terms_and_conditions,
name_on_card,
credit_card_number,
credit_card_expiration_date
) values (
" . $_SESSION['name'] . ",
" . $_SESSION['email_address'] . ",
" . $_SESSION['membership_type'] . ",
" . $_SESSION['terms_and_conditions'] . ",
" . $_POST['name_on_card'] . ",
" . $_POST['credit_card_number'] . ",
" . $_POST['credit_card_expiration_date'] . "
);
//let's run the query
mysql_query($insert_query);
?></p>
<p>[/code]
</code>
Thanks for the script, was helpful athough contains some errors: credit_card_expiration vs. credit_card_expiration_date, and radio buttons should read name= instead of group=.
You can also simply remove the session_register lines. It works without them and this function is discontinued as of php 5.3.
Lucie,
Thank you very much for taking time to post the errors. Corrected now
Thank you for the information. Do you have or know of any tutorials on how to make a multiple page form that can be emailed?
Patty
I’m doing the same thing. It is pretty simple, really. Look up mail functions in PHP. Where you use the $insert_query variable and mysql() function, you’ll use a function like mail() to spit out an email.
On some simple forms, I’ll write the submitted data to a CSV file and then use email to send the same data to someone internally. Works great for those situations where a full db is not required or available.
Thank you so much, Steven.
hey i’ve been trying it out and when i come to processing page it does nothing, i mean not even saved in my database
so i don’t know what i do wrong, i even include(config.php) to connect with database
Hey, very useful for me. With this Code i can finish a new projekt. I’m searching for a email function too. When i find one, i will make a post. Thanks alot, Dany.
Hey could you please tell me the code for emailing the form instead of storing it in the database?
Here’s a basic form with comments so you know what each part does. I’m not sure how to post code here, so let’s hope it works.
<?php
// Set the default timezone
date_default_timezone_set (‘Chicago/New_York’);
// Check for form submission:
if (isset($_POST['submitted'])) {
// Minimal form validation:
if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['comments']) ) {
// Create the body:
$body = “Name: {$_POST['name']}\n\nComments: {$_POST['comments']}”;
// Make it no longer than 70 characters long:
$body = wordwrap($body, 70);
// Send the email:
mail(‘youremailaddress@gmail.com’, ‘Contact Form Submission’, $body, “From: {$_POST['email']}”);
// Redirect user to a new thank you page. This code will not create the page
header(“Location: thank-you.php?n={$_POST['name']}”);
exit();
/*// Print a message instead of redirecting them to a thank you page (take the multiple line comment out
echo ‘<p><em>Thank you for contacting me at ‘ . date(‘g:i a (T)’) . ‘ on ‘ . date(‘l F j, Y’) .’.<br />I will reply some day.</em></p>’;*/
// How long did it all take?
echo ‘<p><strong>It took ‘ . (time() – $_POST['start']) . ‘ seconds for you to complete and submit the form.</strong></p>’;
// Clear $_POST (so that the form’s not sticky):
$_POST = array();
} else {
echo ‘<p class=”error”>Please fill out the form completely.</p>’;
}
} // End of main isset() IF.
?>
<form action=”" method=”post” >
<fieldset>
<legend>Email Form</legend>
<ol>
<li>
<label for=”name”>Name</label>
<input id=”name” name=”name” type=”text” value=”<?php if (isset($_POST['name'])) echo $_POST['name']; ?>” />
</li>
<li>
<label for=”email”>Email Address</label>
<input id=”email” name=”email” type=”text” value=”<?php if (isset($_POST['email'])) echo $_POST['email']; ?>” />
</li>
<li>
<label for=”comments”>Comments</label>
<textarea id=”comments” name=”comments” cols=”30″ rows=”15″><?php if (isset($_POST['comments'])) echo $_POST['comments']; ?></textarea>
</li>
<li>
<input type=”submit” value=”Send!” />
<input type=”hidden” name=”start” value=”<?php echo time(); ?>” />
<input type=”hidden” name=”submitted” value=”TRUE” />
</li>
</ol>
</fieldset>
</form>
when m usins session the warning is come ”
Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:\AppServ\www\Ani\sec.php:5) in C:\AppServ\www\Ani\sec.php on line 6
”
while the souse code for session below…….. please help to correct the problem….
1) <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” ”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

2) <html xmlns=”http://www.w3.org/1999/xhtml”>
3) <head>
4) <meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
5) <?
6) session_start();
7) session_register(‘sec’);
9) $_SESSION['sec'] =$_POST['sec'];
10) ?>
I have the same issue as Anirudh. I have copied and pasted the code directly from here in both Dreamweaver and Notepad++ and I continually get the same error over and over:
Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at http://path.to/form2.php:3) in http://path.to/form2.php on line #
Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at http://path.to/form2.php:3) in http://path.to/form2.php on line #
With “#” being the number of whichever line the “session_start();” function comes into play. Would very much appreciate some feedback on this. Thanks!
You need to start the session before any other information, to include the doctype and head. Take line 5 through 10 and put them before line one. That should help. Without the rest of the code, I don’t really know what you’re trying to do. Sorry.
Yap, figured that out. Another problem I was having with this was that the “‘INSERT INTO subscriptions” line on the final page posted in the tutorial needed to start with a double quote and not a single. Also, it would’ve been helpful mentioning the database connection, selection, and table creation aspects to create an actual working example.
how to create a form using php,html codes which contains array of information about 4 members with for each statement
Great post! Thanks for sharing your knowledge.
Chris
http://www.nirvaha.com/purchase-order.html
Unless than creating like 5 useless session variables for only 1 form, you could create 1 variable(array typed) and make it hold all the values.
so unless then doing this
$_SESSION['EMAIL'] = myadres@hotmail.com
$_SESSION['NAME'] = BOB
$_SESSION['age'] = 20
you would make something like this.
$myarray= array(“userEmail” => $_POST['email'], “userName” => $_POST['name'], “userAge” => $_POST['age']);
$_SESSION['all_info_in_one_variale'] = $myarray
and then just use each index like this..
mytextbox.value = $_SESSION['all_info_in_one_variale']['email'];
mytextbox2.value = $_SESSION['all_info_in_one_variale']['name'];
mytextbox3.value = $_SESSION['all_info_in_one_variale']['age'];
Thanks for the comment
What’s the advantage?
Hi, I have been working for a week trying one solution after another to keep out Duplicate Submissions.
I have an elaborate form that I built in Dreamweaver CS4 that pulls values from another table to populate list selections and checkbox groups (submitting [] arrays comma limited or delimited), etc.
Dreamweaver likes to put the insert record submission script and the form values in the same file so that it submits to itself. But, I can’t make such things work to prevent Duplicate Submissions as found at O’Reilly’s PHP chapters where a session value is used to check if a form has already been submitted, in case of double clicks or refreshing a form after using the browser back button.
A script from O’Reilly included using this in the body of the document before the form code started.
<?
session_start();
$secret=md5(uniqid(rand(), true));
$_SESSION['FORM_SECRET']=$secret;
?>
// then I placed this inside the form itself at the bottom near the Submit button
<input type=”hidden” name=”form_secret” id=”form_secret” value=”<?php echo $_SESSION['FORM_SECRET'];?>” />
Then I tried a million ways to incorporate this…..
/Retrieve the value of the hidden field
$form_secret=$_POST['form_secret'];
if(isset($_SESSION['FORM_SECRET'])) {
if(strcasecmp($form_secret,$_SESSION['FORM_SECRET'])===0) {
/*Put your form submission code here
After processing the form data,
unset the secret key from the session
*/
unset($_SESSION['FORM_SECRET']);
}else {
//Invalid secret key
}
}else {
//Secret key missing
echo ‘Form data has already been processed!’;
}
I put all the processing script inside but I usually got “Form data has already been processed” even when the browser and file on the localhost test site was refreshed.
In your 3 file method how would you help to eliminate accidental or deliberate double submissions of the same form?
I have made extra database fields for such values as “token”, “session”, “unique_id” in trying other ways to pre-check the submission form to see if it has values that match what have already been saved.
I am guessing this is easier to do in a multi file process.
I look forward to your suggestions!
i am a novice webdeveloper i am making html forms and integrating the data using mysql and php into database..the only thing i am having problem is wirh the order pages i am done with the registration and login page the data gets filled in database with $con(-do-) …… commands ..i want to know for the oder page i dnt have forms but only text field = quantity and color = dropdown list and submit button
so on submit how do i update this things into my database…please help..
thank you very much for this tutorial.this is very easy and quick multi page registration form.
i bookmarked your this page.you are really great.i definitely suggest to my friend.
thank you again
How do you pass hidden field values to another page?
i used the above code for my application but when i submit my form i wont see the form data in mysql database please help
Hey Guys, this is my code….
<?php
//let’s start our session, so we have access to stored data
include(‘config.php’);
session_start();
//let’s create the query
$insert_query = ‘insert into account (
name,
email,
membership_type,
terms_condition,
card,
card_no,
expiration_date
) values (
” . $_SESSION['name'] . “,
” . $_SESSION['email_address'] . “,
” . $_SESSION['membership_type'] . “,
” . $_SESSION['terms_and_conditions'] . “,
” . $_POST['name_on_card'] . “,
” . $_POST['credit_card_number'] . “,
” . $_POST['credit_card_expiration_date'] . ”
);
//let’s run the query
mysql_query($insert_query);
?>
When I’ve run then it just display an error….
Parse error: syntax error, unexpected T_STRING in C:\xampp\htdocs\test2\form_process.php on line 18
Please help me to remove this error…
It should be “insert into account (
and
” . $_POST['credit_card_expiration_date'] . “)”;
Great post this helped me alot thanks
Great easy to follow solution. You’ll be getting a StumbleUpon like from me for this one! If I wanted to capture the first/second page details into MySQL I’m assuming these could just be inserted as you go? But could you shed any light on how I could save all partially complete forms without ending up with duplicate data?
Next Comments →