May
04
2009

Processing Multiple Forms on One Page with PHP

by   |  Posted in Tutorials  |  30 comments

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.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , , , , , , ,

Short URL: http://bit.ly/d5WKeI

Discussion 30 Comments

  1. Dez Futak on May 5, 2009 at 5:20 am

    Very nicely explained & a useful tip – many thanks!

    Dez.

  2. Still Lost on June 23, 2009 at 8:25 pm

    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!

  3. Akshay on July 24, 2009 at 10:15 am

    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.

    • c.bavota on July 27, 2009 at 8:07 am

      Sure. Just use Sessions to move the information to the second page.

  4. Howida on October 21, 2009 at 5:52 am

    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.

    • c.bavota on October 21, 2009 at 10:38 am

      To move information from one page to the next you can use $_POST. Make sure your form has method="post" set and then on the second form, display the information from the first form by using

      <?php echo $_POST['input-name']; ?>

      as the value for the new input fields.

  5. Onno on November 16, 2009 at 4:31 pm

    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

  6. moek on November 22, 2009 at 12:16 am

    very nice explanation! which I search 3days along. thanks a lot…

  7. Geniuzs on March 25, 2010 at 11:39 am

    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.

  8. Butch7070 on April 13, 2010 at 9:40 am

    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.

  9. Gursel on April 25, 2010 at 5:57 pm

    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.

  10. v on July 8, 2010 at 5:31 pm

    That’s useless because it doesn’t change anything. It’s better using form action because it keeps the code more organized.

  11. guest on August 11, 2010 at 11:52 am

    if (array_key_exists(‘contact’, $_POST)) {
    should be

    if (array_key_exists(‘contactus’, $_POST)) {

    • c.bavota on August 12, 2010 at 1:11 pm

      Oops. Thanks for the correction.

  12. Jose on August 21, 2010 at 1:01 pm

    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: &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    Password:

    &nbsp&nbsp
    &nbsp

    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

    • c.bavota on August 21, 2010 at 1:52 pm

      Which line is line 146?

  13. Jose on August 21, 2010 at 1:05 pm

    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

    • Deadcow on September 11, 2010 at 5:14 am

      You’ve missed a bracket out.

      if(array_key_exists(“form2″,$_POST)
      {…

      should read:

      if(array_key_exists(“form2″,$_POST))
      {…

  14. Carl on September 5, 2010 at 12:36 am

    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?

    • c.bavota on September 8, 2010 at 9:34 am

      Sounds like you might need to use some Javascript or jQuery to get your forms acting the way you want.

  15. Carl on September 5, 2010 at 12:39 am

    sorry for the typo’s. been behind the keyboard since 9am and it is now 11:40 pm…

  16. Ryan on September 27, 2010 at 5:08 pm

    Just what I was looking for, thanks very much appreciate your time to share this.

  17. Varsha on November 2, 2010 at 8:41 am

    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.

  18. Tom on November 9, 2010 at 7:27 am

    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;
    }
    
    • c.bavota on November 9, 2010 at 3:21 pm

      You are totally right. That is actually how I now do it. I should redux this tutorial.

  19. Mike Bundrant on December 22, 2010 at 2:41 am

    4 days and counting…until I found this. Thanks much.

  20. Alex Aucter on January 29, 2011 at 2:56 pm

    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!

  21. RobetE on February 12, 2011 at 9:17 am

    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 :-(

  22. mc jam bi on April 16, 2011 at 12:17 pm

    thansk ! i am having trouble with multy form in html