A multi page form in PHP can be created using sessions, that are used to retain values of a form and can transfer them from one page to another .
By seeing popularity of such forms, we bring this tutorial to create a multi page form using PHP script. However, we have already covered multi step form using jQuery and JavaScript.
In our example, we have used :
- PHP sessions to store page wise form field values in three steps.
- Also, we have applied some validations on each page.
- At the end, we collects values from all forms and store them in a database.
Watch our live demo or download our codes to use it.
Our complete HTML and PHP codes are given below.
PHP file: page1_form.php
Given below are the codes for first part of the form, as user fills it and clicks on next button, it will redirect to second page .
<?php
session_start(); // Session starts here.
?><!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2>
<span id="error">
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
</span>
<form action="page2_form.php" method="post">
<label>Full Name :<span>*</span></label>
<input name="name" type="text" placeholder="Ex-James Anderson" required>
<label>Email :<span>*</span></label>
<input name="email" type="email" placeholder="[email protected]" required>
<label>Contact :<span>*</span></label>
<input name="contact" type="text" placeholder="10-digit number" required>
<label>Password :<span>*</span></label>
<input name="password" type="Password" placeholder="*****" />
<label>Re-enter Password :<span>*</span></label>
<input name="confirm" type="password" placeholder="*****" >
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</form>
</div>
</div>
</body>
</html>
PHP file: page2_form.php
In the below script, we validate all fields of page1 and set sessions for page1 errors.
<?php
session_start();
// Checking first page values for empty,If it finds any blank field then redirected to first page.
if (isset($_POST['name'])){
if (empty($_POST['name'])
|| empty($_POST['email'])
|| empty($_POST['contact'])
|| empty($_POST['password'])
|| empty($_POST['confirm'])){
// Setting error message
$_SESSION['error'] = "Mandatory field(s) are missing, Please fill it again";
header("location: page1_form.php"); // Redirecting to first page
} else {
// Sanitizing email field to remove unwanted characters.
$_POST['email'] = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// After sanitization Validation is performed.
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
// Validating Contact Field using regex.
if (!preg_match("/^[0-9]{10}$/", $_POST['contact'])){
$_SESSION['error'] = "10 digit contact number is required.";
header("location: page1_form.php");
} else {
if (($_POST['password']) === ($_POST['confirm'])) {
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
} else {
$_SESSION['error'] = "Password does not match with Confirm Password.";
header("location: page1_form.php"); //redirecting to first page
}
}
} else {
$_SESSION['error'] = "Invalid Email Address";
header("location: page1_form.php");//redirecting to first page
}
}
} else {
if (empty($_SESSION['error_page2'])) {
header("location: page1_form.php");//redirecting to first page
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2><hr/>
<span id="error">
<?php
// To show error of page 2.
if (!empty($_SESSION['error_page2'])) {
echo $_SESSION['error_page2'];
unset($_SESSION['error_page2']);
}
?>
</span>
<form action="page3_form.php" method="post">
<label>Religion :<span>*</span></label>
<input name="religion" id="religion" type="text" value="" >
<label>Nationality :<span>*</span></label><br />
<input name="nationality" id="nationality" type="text" value="" >
<label>Gender :<span>*</span></label>
<input type="radio" name="gender" value="male" required>Male
<input type="radio" name="gender" value="female">Female
<label>Educational Qualification :<span>*</span></label>
<select name="qualification">
<option value="">----Select----</options>
<option value="graduation" value="">Graduation </options>
<option value="postgraduation" value="">Post Graduation </options>
<option value="other" value="">Other </options>
</select>
<label>Job Experience :<span>*</span></label>
<select name="experience">
<option value="">----Select----</options>
<option value="fresher" value="">Fresher </options>
<option value="less" value="">Less Than 2 year </options>
<option value="more" value="">More Than 2 year</options>
</select>
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</form>
</div>
</div>
</body>
</html>
PHP file: page3_form.php
In the below script, we validate all fields of page2 and set sessions for page2 errors.
<?php
session_start();
// Checking second page values for empty, If it finds any blank field then redirected to second page.
if (isset($_POST['gender'])){
if (empty($_POST['gender'])
|| empty($_POST['nationality'])
|| empty($_POST['religion'])
|| empty($_POST['qualification'])
|| empty($_POST['experience'])){
$_SESSION['error_page2'] = "Mandatory field(s) are missing, Please fill it again"; // Setting error message.
header("location: page2_form.php"); // Redirecting to second page.
} else {
// Fetching all values posted from second page and storing it in variable.
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
}
} else {
if (empty($_SESSION['error_page3'])) {
header("location: page1_form.php");// Redirecting to first page.
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2><hr/>
<span id="error">
<?php
if (!empty($_SESSION['error_page3'])) {
echo $_SESSION['error_page3'];
unset($_SESSION['error_page3']);
}
?>
</span>
<form action="page4_insertdata.php" method="post">
<b>Complete Address :</b>
<label>Address Line1 :<span>*</span></label>
<input name="address1" id="address1" type="text" size="30" required>
<label>Address Line2 :</label>
<input name="address2" id="address2" type="text" size="50">
<label>City :<span>*</span></label>
<input name="city" id="city" type="text" size="25" required>
<label>Pin Code :<span>*</span></label>
<input name="pin" id="pin" type="text" size="10" required>
<label>State :<span>*</span></label>
<input name="state" id="state" type="text" size="30" required>
<input type="reset" value="Reset" />
<input name="submit" type="submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
PHP file: page4_form.php
Here, we collects values of all pages and store them in database.
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2>
<?php
session_start();
if (isset($_POST['state'])) {
if (!empty($_SESSION['post'])){
if (empty($_POST['address1'])
|| empty($_POST['city'])
|| empty($_POST['pin'])
|| empty($_POST['state'])){
// Setting error for page 3.
$_SESSION['error_page3'] = "Mandatory field(s) are missing, Please fill it again";
header("location: page3_form.php"); // Redirecting to third page.
} else {
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']); // Function to extract array.
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("phpmultipage", $connection); // Storing values in database.
$query = mysql_query("insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')", $connection);
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
unset($_SESSION['post']); // Destroying session.
}
} else {
header("location: page1_form.php"); // Redirecting to first page.
}
} else {
header("location: page1_form.php"); // Redirecting to first page.
}
?>
</div>
</div>
</body>
</html>
MySQL Codes:
To create table in MySQL Database.
CREATE TABLE detail (
user_id int(10) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
contact int(15) NOT NULL,
password varchar(255) NOT NULL,
religion varchar(255) NOT NULL,
nationality varchar(255) NOT NULL,
gender varchar(255) NOT NULL,
qualification varchar(255) NOT NULL,
experience varchar(255) NOT NULL,
address1 varchar(255) NOT NULL,
address2 varchar(255) NOT NULL,
city varchar(255) NOT NULL,
pin int(10) NOT NULL,
state varchar(255) NOT NULL,
PRIMARY KEY (user_id)
)
CSS File: style.css
Styling HTML elements.
@import url(http://fonts.googleapis.com/css?family=Raleway);
div.container{
width: 960px;
height: 610px;
margin:50px auto;
}
div.main{
width: 308px;
margin-top: 35px;
float:left;
border-radius: 5px;
Border:2px solid #999900;
padding:0px 50px 20px;
font-family: 'Raleway', sans-serif;
}
#error{
display:block;
margin-top: 10px;
margin-bottom: 10px;
}
#success{
color:green;
font-weight:bold;
}
span{
color:red;
}
h2{
background-color: #FEFFED;
padding: 32px;
margin: 0 -50px;
text-align: center;
border-radius: 5px 5px 0 0;
}
b{
font-size:18px;
display: block;
color: #555;
}
hr{
margin: 0 -50px;
border: 0;
border-bottom: 1px solid #ccc;
margin-bottom:25px;
}
label{
color: #464646;
font-size: 14px;
font-weight: bold;
}
input[type=text],
input[type=password],
input[type=number],
input[type=email]{
width:96%;
height:25px;
padding:5px;
margin-top:5px;
margin-bottom:15px;
}
input[type=radio]
{
margin:20px;
}
select{
margin-bottom: 15px;
margin-top: 5px;
width: 100%;
height: 35px;
font-size: 16px;
font-family: cursive;
}
input[type=submit],
input[type=reset]{
padding: 10px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #524f49;
cursor: pointer;
width: 49.2%;
border-radius: 2px;
margin-bottom: 15px;
font-weight:bold;
font-size:16px;
}
input[type=submit]:hover,
input[type=reset]:hover
{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
Conclusion:
This was all about, to create multi page form in PHP that would have helped you a lot. Always provide us your valuable feedback and do visit again for getting more coding tricks.
20 Replies to “PHP Multi Page Form”
its really cool dude… thanks for this
Hi,
Thanks a lot for your great tutorial. Just could you please help me know how I can insert data with PDO ? (I tried it but it insert nothing in DB )
try{
$conn = new PDO(‘mysql:dbname=Application;host=localhost;charset=utf8’, ‘user’, ‘pass’);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare(‘INSERT INTO test (q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20, q21, q22, q23, q24, q25) VALUES (:q1, :q2, :q3, :q4, :q5, :q6, :q7, :q8, :q9, :q10, :q11, :q12, :q13, :q14, :q15, :q16, :q17, :q18, :q19, :q20, :q21, :q22, :q23, :q24, :q25)’);
$stmt->execute(array(‘:q1′ => $q1,’:q2′ => $q2, ‘:q3’ => $q3, ‘:q4’ => $q4, ‘:q5’ => $q5, ‘:q6’ => $q6, ‘:q7’ => $q7, ‘:q8’ => $q8, ‘:q9’ => $q9, ‘:q10’ => $q10, ‘:q11’ => $q11, ‘:q12’ => $q12, ‘:q13’ => $q13, ‘:q14’ => $q14, ‘:q15’ => $q15, ‘:q16’ => $q16, ‘:q17’ => $q17, ‘:q18’ => $q18, ‘:q19’ => $q19, ‘:q20’ => $q20, ‘:q21’ => $q21, ‘:q22’ => $q22, ‘:q23’ => $q23, ‘:q24’ => $q24, ‘:q25’ => $q25));
}
catch(Exception $e) {
echo ‘Exception -> ‘;
var_dump($e->getMessage());
}
header(‘Location: Thankyou.php’);
exit;
Yes we will definitely cover that topic in our upcoming blog posts.
Keep reading to catch it up.
it is giving me undefined variable when i try to extract session in local environment.
Thanks
Himesh
It’s actually a cool and useful piece of information. I’m glad that you just shared this helpful
info with us. Please keep us up to date like
this. Thanks for sharing.
I know your focus isn’t on security with this post- but it’s totally irresponsible to write an article like this, think it’s okay to drop user supplied strings into a database unescaped, and then plop the article onto the web for newbies learning how to program to use. On top of that you’re using deprecated mysql_* functions. Please tell me you have never used this on a live site. Please only post code when you’re sure it won’t ruin someone’s day. And on top of that you’ve taught people how to store plaintext passwords AND store the password in $_SESSION…. holy hell.
Please google and understand the following concepts:
SQL injection *biggie
XSRF
Plaintext Passwords *biggie
PHP extract() security implications http://security.stackexchange.com/questions/36538/exploiting-php-via-get-params
I didn’t see it in your code but I’ll also wager: Sanitizing Html *biggie
Hi Dan
If i was to use this with wordpress, would it be safe?
If i ignore the database he recommended, and pointed the form to fill in the wordpress database?
Thanks
great tutorial working fine boss
Hey and,what if I want to send all the data to my email?
Buddy all is ok but you forget to store data into database from form 1 and form 2 . it just showing only 3rd form data on database.please correct your code .
This form in not working properly. it give me a error I can show you.
Warning
: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at D:\xampp\htdocs\Ajax_multi_form\page4_insertdata.php:12) in
D:\xampp\htdocs\Ajax_multi_form\page4_insertdata.php
on line
13
Warning
: Cannot modify header information – headers already sent by (output started at D:\xampp\htdocs\Ajax_multi_form\page4_insertdata.php:12) in
D:\xampp\htdocs\Ajax_multi_form\page4_insertdata.php
on line
49
Please give me some solution for it.
Hi! Cool tutorial! This info seems to be nowhere else on the web in such a clear form) One question though: can you give a hint, how should page4_form.php be modified in order to send a letter with @mail including all the user-entered data? Here is my code for page4_form.php. What am I doing wrong?
$value) {
$_SESSION[‘post’][$key] = $value;
}
extract($_SESSION[‘post’]); // Function to extract array.
$email_message .= “Example1: “. $address1.”\n”;
$email_message .= “Example2: “. $address2.”\n”;
$email_message .= “Example3: “. $gender.”\n”;
$email_from = “[email protected]”;
$email_to = “[email protected]”;
$email_subject = “just a test”;
$headers = ‘From: ‘.$email_from.”\r\n”.
‘Reply-To: ‘.$email_from.”\r\n” .
‘X-Mailer: PHP/’ . phpversion();
$sendit = @mail(“[email protected]”, “JustATest”, $email_message, $headers);
/* unset($_SESSION[‘post’]); // Destroying session. */
if ($sendit)
{
echo “Success”;
}
else
{
echo “Failure”;
}
?>
Will this code work if you have multiple tables to insert values into, just changing how the mysql_query handles it at the end of the form?
No idea why this wont work in wordpress..
Only when going to the next page its coming up with 404 page not found..
then refreshing the page it appears.
No idea why the page isint appearing
Weird
It really helpful. Can you please show us how to display back the information that user input in the form previously which saved in the database. It is super really helpful for me to finish my assignment which are related to my question. Thank you.
Nice Tutorial for beginners.
Its really helpful code,, i apply to it,,and its working,,,,but can you please help me in how to retain values if error message arrives……in this above code…that is PHP Multi Page Form
Cool, thanks for sharing !!!
Just a little bug:
In page3_form.php line 43 appears and must be page4_form.php (or change the name of the fourth file to page4_insertdata.php…
Also, it doesn´t work on PHP 7 (because the mysql command it´s not allowed anymore)… I´m trying to improve the MySQLi function on connections and querys. If it works I´ll show you.
Thanks again !!!
Yes, it´s work perfect with MySQLi !!!
I just change al the lines tha includes mysql sentence and change it like this:
$connect= new mysqli(‘localhost’, ‘root’, ‘password’, ‘phpmultipage’);
if (mysqli_connect_errno())
{
echo “No se pudo conectar con MySQL: ” . mysqli_connect_error();
}
$query = mysqli_query($connect,”INSERT INTO detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) VALUES (‘$name’,’$email’,’$contact’,’$password’,’$religion’,’$nationality’,’$gender’,’$qualification’,’$experience’,’$address1′,’$address2′,’$city’,’$pin’,’$state’)”);
And don´t forget to change the name of the fourth file (or change it on the page3_form.php file).
Good luck !!
You said “However, we have already covered multi step form using jQuery and JavaScript” – could you please provide a link to where you did that?