Processing Multiple Forms on One Page with PHP
I know that the way most people treat multiple forms on one page is to have each form post to another PHP file where the form is validated, its information is entered into a database or an email is sent off. So you usually have something like this:
<form name="contactform" method="post" action="sendmail.php"> blah blah blah </form> <form name="mailinglist" method="post" action="join.php"> blah blah blah </form> |
That work great, but why would you create all those extra files when you can just have the form post to the same file and create multiple functions to process your multiple forms.
The solution is very simple and super efficient.
First, lets create some forms.
<form name="mailinglist" method="post"> <input type="text" name="email" /> <input type="submit" name="mailing-submit" value="Join Our Mailing List" /> </form> <form name="contactus" method="post"> <input type="text" name="email" /> <input type="text" name="subjet" /> <textarea name="message"></textarea> <input type="submit" name="contact-submit" value="Send Email" /> </form> |
Now lets put some PHP code before the <head> tag to have different processes for each form.
<?php if (!empty($_POST['mailing-submit'])) { //do something here; } if (!empty($_POST['contact-submit'])) { //do something here; } ?> |
Now all you need to do is create your processes within those two “if” statements and each form will be dealt with accordingly when it it filled and submitted.



Very nicely explained & a useful tip – many thanks!
Dez.
Hey, thanks for the info, but how about showing specifically how to connect the sendmail.php and the join.php to the if statements you made and maybe adding an error notice or die switch if one form is not complete.
I’m going to assume we just need to put the action within the if statement but I am not sure. I am going to go workout try it and then come back if I still don’t get the results I want.
Thanks again!
hey !thanks alot,but can u pls tell me how can i process multiple forms on 2 different pages.In other words dividing a simple form into 2 pages and then processing it.
Pls reply soon.
Sure. Just use Sessions to move the information to the second page.
thank you for te valuable information. how can i show two forms in one form based on a click from one of the forms. i.e:
i want to show one form with a button, after submitting that form another form will be displayed on the same page containg the information of that form being submitted.
To move information from one page to the next you can use
$_POST. Make sure your form hasmethod="post"set and then on the second form, display the information from the first form by usingas the value for the new input fields.
Here’s how to post two forms at once (to the same script):
http://tech.solin.eu/doku.php?id=webdev:submitting_multiple_forms_at_once
This solution relies on the javascript prototype library. There are also various jQuery solutions out there.
Onno
very nice explanation! which I search 3days along. thanks a lot…
Wow… you have really made my life simple…Thanks a million… you have saved me writing out code that took ages to write and also cleared up so much clutter that I used to make while writing separate scripts for these forms.
I have to admit, that’s pretty slick. The reason I would go ahead and do it the other way is for maintainability. I can easily look through my files and see that the join.php file probably contains the code for joining, whereas I would have to open up the file with multiple forms to see which file it calls, then look through that file and spend time searching through the code to find where the functionality lies for joining the site.
Doing it the old way does create a lot of files, but they are small and they each meet one of the OO goals: “Do one thing and do it well”
Creating one massive file to have different functionality based on input, while educationally intriguing, is hard to maintain and means that the php parser has to parse through code that isn’t even usable for the given context.
That’s just my $.02, take it for what it’s worth.
Thank you so much for the code. I was about to pull my hair out and i stumbled across this script and it works beautifully.
That’s useless because it doesn’t change anything. It’s better using form action because it keeps the code more organized.
if (array_key_exists(‘contact’, $_POST)) {
should be
if (array_key_exists(‘contactus’, $_POST)) {
Oops. Thanks for the correction.
page
body {
background-repeat: repeat-x;
font-family: Century Gothic,Arial,Verdana;
font-color: #000000;
}
input.btn {
color:#FFFFFF;
font: bold 84% ‘trebuchet ms’,helvetica,sans-serif;
background-color:#f88a8a;
border: 1px solid;
border-color: #FF0000;
filter:progid:DXImageTransform.Microsoft.Gradient
(GradientType=0,StartColorStr=’#ffffffff’,EndColorStr=’#ffeeddaa’);
}
input.signup {
color:#FFFFFF;
width: 100px;
height: 40px;
font: bold 84% ‘trebuchet ms’,helvetica,sans-serif;
background-color:#44a947;
border: 1px solid;
border-color: #24FF00;
filter:progid:DXImageTransform.Microsoft.Gradient
(GradientType=0,StartColorStr=’#ffffffff’,EndColorStr=’#ffeeddaa’);
}
.textbox {
color: #000000;
width: 200px;
height: 30px;
font: bold 84% ‘trebuchet ms’,helvetica,sans-serif;
}
Email:                                
Password:
  
 
Sign Up
It’s free, and always will be.
Name:
Your Email Address:
Password:
Gender:
Select Sex:
Male
Female
Birthday:
Month:JanFebMarAprMay
JunJulAugSepOctNov
Dec
Day:123456
78910111213
141516171819
20212223242526
2728293031
Year:2010200920082007200620052004200320022001
20001999199819971996199519941993199219911990
198919881987198619851984198319821981198019791978
197719761975197419731972197119701969196819671966
1965196419631962196119601959195819571956195519541953
195219511950194919481947194619451944
1943194219411940
Create a Page for a celebrity, band or business.
<?php
$dbconnect = mysql_connect("localhost", "root", "") or die ("Unable to Connect". mysql.error());
$dbselect = mysql_select_db(matchmakerdb, $dbconnect);
if(array_key_exists("form2",$_POST)
{
if(isset($_GET["error"])) {
$error = $_GET["error"];
if ($error == 1) {
echo "Username and/or password invalid”; }
}
if($_POST['Sign Up'] == ‘Sign Up’)
{
$name = $_POST["name"];
$email = $_POST['eadd'];
$gender = $_POST["gender"];
$bday = $_POST["birthyear"].$_POST["birthmonth"].$_POST["birthdate"];
$password = $_POST['pw'];
$log = mysql_query(“SELECT * FROM tblaccount WHERE email=’$email’”);
$cell = mysql_fetch_array($log);
if($_POST['Sign Up'] == ‘Sign Up’)
{
if ($name == NULL || $gender == NULL || strlen($password) < 8 || $password == NULL)
{
echo "Invalid Input!”;
}
elseif(strchr($email,’@') == NULL || strchr($email, ‘.com’) == NULL)
{
echo “Invalid Email Address!”;
}
else if ($email == $cell['email'])
{
echo “Email address already used!”;
}
else {
mysql_query(“INSERT INTO tblaccount (name, email, password, gender, bday) VALUES (‘$name’, ‘$email’, ‘$password’, ‘$gender’, ‘$bday’)”);
echo “Record saved”;
}
}
}
?>
that error is Parse error: syntax error, unexpected ‘{‘ in C:\xampp\htdocs\xampp\login\samp.php on line 146
Which line is line 146?
Name:
Your Email Address:
Password:
Gender:
Select Sex:
Male
Female
<?php
$dbconnect = mysql_connect("localhost", "root", "") or die ("Unable to Connect". mysql.error());
$dbselect = mysql_select_db(matchmakerdb, $dbconnect);
if(array_key_exists("form2",$_POST)
{
if(isset($_GET["error"])) {
$error = $_GET["error"];
if ($error == 1) {
echo "Username and/or password invalid”; }
}
if($_POST['Sign Up'] == ‘Sign Up’)
{
$name = $_POST["name"];
$email = $_POST['eadd'];
$gender = $_POST["gender"];
$bday = $_POST["birthyear"].$_POST["birthmonth"].$_POST["birthdate"];
$password = $_POST['pw'];
$log = mysql_query(“SELECT * FROM tblaccount WHERE email=’$email’”);
$cell = mysql_fetch_array($log);
if($_POST['Sign Up'] == ‘Sign Up’)
{
if ($name == NULL || $gender == NULL || strlen($password) < 8 || $password == NULL)
{
echo "Invalid Input!”;
}
elseif(strchr($email,’@') == NULL || strchr($email, ‘.com’) == NULL)
{
echo “Invalid Email Address!”;
}
else if ($email == $cell['email'])
{
echo “Email address already used!”;
}
else {
mysql_query(“INSERT INTO tblaccount (name, email, password, gender, bday) VALUES (‘$name’, ‘$email’, ‘$password’, ‘$gender’, ‘$bday’)”);
echo “Record saved”;
}
}
}
?>
that error is unexpected { in if(array_key_exists(“form2″,$_POST)
{
please help me
You’ve missed a bracket out.
if(array_key_exists(“form2″,$_POST)
{…
should read:
if(array_key_exists(“form2″,$_POST))
{…
I have a php page with two forms. First one reads database and populates a drop down list. Second form is populated based on selection from first for. (name selected from first form, personal profile edited by second form). First form has action of self, second calls a php script to updata database. Table names and submit button names are unique. Clicking second button does not coll the script, but executes a self command and regenerates the page. Any suggestions?
Sounds like you might need to use some Javascript or jQuery to get your forms acting the way you want.
sorry for the typo’s. been behind the keyboard since 9am and it is now 11:40 pm…
Just what I was looking for, thanks very much appreciate your time to share this.
I want multiple forms on one HTML page. From form1, need a ‘next’ until form5, which will have a ‘submit’ button. Need to capture the data and send it as an email.
Please guide.
You should take a look at this: http://flowplayer.org/tools/demos/scrollable/wizard.html
Why bother with the hidden input tags? Why not just give the submit buttons different names and determine which submit button was clicked like this?
if ($_POST['button_name']){ //do something here; }You are totally right. That is actually how I now do it. I should redux this tutorial.
4 days and counting…until I found this. Thanks much.
Hello there! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a wonderful job!
Will it also work for multi page forms system? sorry im not an expert in php but assigned a simple project and have to do it alone
thansk ! i am having trouble with multy form in html