It's not completely unheard of to do this. Quite often, a different parameter is passed in the form element's action attribute like /submit.php?action=register or /submit.php?action=activate.

So, you have code like this:

if ($_GET['action'] == 'register') {
  // Register user
} else if($_GET['action'] == 'activate' {
  // Activate user
}

However, you could also just change the value of the submit button and have the action attribute the same for both forms:

if (isset($_POST['submit'])) {
  if ($_POST['submit'] == 'register') {
    // Register user
  } else if($_POST['submit'] == 'activate') {
    // Activate user
  }
}
Answer from Ami on Stack Overflow
🌐
Source Code Tester
sourcecodester.com › tutorials › php › 13495 › php-multiple-form-inputs.html
How to Submit Multiple Form Inputs in PHP Tutorial | SourceCodester
In this tutorial we will create a Multiple Form Inputs using PHP. This code will allow the user to insert multiples forms of data to the database server when the user clicks the submit button.
Discussions

html - How to process multiple forms using one php script - Stack Overflow
I have multiple forms and I have one php script that I want to use to process these forms but when I click on submit for any of the forms...the script is processed by the number of forms with the s... More on stackoverflow.com
🌐 stackoverflow.com
October 21, 2011
Multiple Forms on One Page - PHP - SitePoint Forums | Web Development & Design Community
Under each Article on my website, members can post Comments. And beneath each Comment, other members can give the Comment a rating. So if there are 30 Comments, I would have 30 Forms!! What is the proper way to set up my Forms and Submit buttons so they work properly? Here is an example… More on sitepoint.com
🌐 sitepoint.com
0
July 19, 2014
html - How to handle multiple php forms using one php page - Stack Overflow
I'm a student and I know nothing about PHP. but I have to do one of my assignment using PHP. Here is the problem which I faced. On my index page, there are 3 links that direct to 3 different forms... More on stackoverflow.com
🌐 stackoverflow.com
Handling multiple forms across a website in PHP
Alex Watts is having issues with: Hello, I have a website which includes multiple forms across different webpages. I would like to have a single page called process... More on teamtreehouse.com
🌐 teamtreehouse.com
0
March 2, 2017
🌐
Reddit
reddit.com › r/php › php multiple forms best practice
r/PHP on Reddit: PHP Multiple Forms Best Practice
July 22, 2017 -

I'm new to PHP, so this question might be self-explanatory given more knowledge of the language.

When handling multiple forms from the same html file, what is the best practice in terms of PHP file structure? Should each form be pointing to a different PHP file, should a single PHP file handle every form somehow?

Thanks for the advice in advance.

Top answer
1 of 5
7

when I click on submit for any particular form, it submits all the forms.

this is not true.
Once your forms have proper formatting, your browser will submit only current one.
(and PHP has nothing to do here)

however, whole page will be reloaded, if you mean that. That is okay - when you submit a form, a page is intended to reload. If you need another behavior, you have to explain your wishes.

Also note that none of your text fields being sent to the server as they have no names.

I guess the question I should be asking is, how do I pass a particular form to php instead of writing multiple php scripts to handle each form!!!

well, it seems you want to ask how to distinguish these forms.

add a hidden field into each

<input type="hidden" name="step" value="1" />

and then in PHP

if ($_POST['step'] == 1) {
  //first form
}
if ($_POST['step'] == 2) {
  //second
}
2 of 5
3

This submits one form of many to php. Copy, paste, test, and study.

<?php
     if (isset($_POST['submitForm'])) { 

    print_r($_POST);

     }

?>
<form action="" name="form1" method="post">
<input type="text" value="" name="A" />
<input type="text" value="" name="B" />
<input type="text" value="" name="C" />
<input type="text" value="" name="D" />
<input type="Submit" value="Submit Form" name="submitForm" />
</form>

<form action="" name="form2" method="post">
<input type="text" value="" name="A" />
<input type="text" value="" name="B" />
<input type="text" value="" name="C" />
<input type="text" value="" name="D" />
<input type="Submit" value="Submit Form" name="submitForm" />
</form>

<form action="" name="form3" method="post">
<input type="text" value="" name="A" />
<input type="text" value="" name="B" />
<input type="text" value="" name="C" />
<input type="text" value="" name="D" />
<input type="Submit" value="Submit Form" name="submitForm" />
</form>

Using a,b,c,d for the first form, e,f,g,h for the second form and i,j,k,l for the third form and submitting the second form yields the following output:

Array
(
    [A] => e
    [B] => f
    [C] => g
    [D] => h
    [submitForm] => Submit Form
)
🌐
Bavotasan
bavotasan.com › home › processing multiple forms on one page with php
Processing Multiple Forms on One Page with PHP - bavotasan.com
October 30, 2012 - <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.
🌐
SitePoint
sitepoint.com › php
Multiple Forms on One Page - PHP - SitePoint Forums | Web Development & Design Community
July 19, 2014 - Under each Article on my website, members can post Comments. And beneath each Comment, other members can give the Comment a rating. So if there are 30 Comments, I would have 30 Forms!! What is the proper way to set up my Forms and Submit buttons so they work properly? Here is an example…
🌐
TechRepublic
techrepublic.com › home › handling multiple submits in a single form with php
Handling multiple submits in a single form with PHP - TechRepublic
June 8, 2007 - If you have a large number of submit buttons to deal with, this approach is easier to read and understand than multiple if-else blocks. But what about the case where you’ve got graphical submit buttons instead of text-based? A minor twist in the tale comes if you use a graphical submit button, as in the following simple form: ... <form action=”processor.php” method=”post”> Search for: <input type=”text” name=”q”> <input type=”image” name=”go” src=”/images/go.gif”> </form>
Find elsewhere
🌐
HTML Form Guide
html.form.guide › php-form › php-order-form
Creating a multi-page order form using PHP | HTML Form Guide
<?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']; ?>
🌐
FormGet
formget.com › home › php › php multi page form
PHP Multi Page Form | FormGet
July 24, 2014 - Sessions in PHP are used to retain values of a web page and can transfer them from one page to another. Using this property, we can create a multipage form in PHP.
🌐
Team Treehouse
teamtreehouse.com › community › handling-multiple-forms-across-a-website-in-php
Handling multiple forms across a website in PHP (Example) | Treehouse Community
March 2, 2017 - On a site that i manage which has many forms, i have a process.php file for each form. I'm afraid that if i try to bundle everything into a single php file it can become unmanageable. Here is a thread i found on the topic http://stackoverflow.com/questions/10459012/multiple-forms-and-one-processing-page
🌐
Reddit
reddit.com › r/phphelp › need help with multiple forms on one page, here
r/PHPhelp on Reddit: Need help with multiple forms on one page, here
April 5, 2023 -

https://pastebin.com/qxigq13B

Apologies if my wording seems kind of vague here, but here goes:

For each row of mySql data that is returned, I want to make the row data its own form, include either a select menu (or a number input) and push them (both row data and input value) into an array on another file. The issue is, if I use $_GET or $_POST, the row items won't come through, and if I were to use $_SESSION, it would only take row data from the last form without including the value of the number/select input. Included is a relevant code snippet, with the number or select fields omitted.

🌐
SitePoint
sitepoint.com › php
Submit multiple form with one button - PHP - SitePoint Forums | Web Development & Design Community
June 28, 2022 - im trying to insert data into database with two different form into two different tables with single button. Both Form are in same page. Form-1 (inserts data in table-1) if(isset($_POST['form_1'])){ Insert Query w…
Top answer
1 of 4
5

Have you tried to do it with $.ajax? You can add an foreach, or call another form on the Onsucces function. Another approach is changing all to one form with an array that points to the right "abstract" form:

Copy<form action="" method="post">
    <input type="text" name="name[]">
    <input type="text" name="example[]">

    <input type="text" name="name[]">
    <input type="text" name="example[]">

    <input type="text" name="name[]">
    <input type="text" name="example[]">

    <button id="clickAll">Submit All</button>
</form>

And in php:

Copyforeach ($_POST['name'] as $key => $value) {
    $_POST['name'][$key]; // make something with it
    $_POST['example'][$key];  // it will get the same index $key
}
2 of 4
0

Here is a working jsFiddle: http://jsfiddle.net/SqF6Z/3/

Basically, add a class to each form and trigger() a submit on that class. Like so:

HTML (example only):

Copy<form action="http://www.google.com" method="get" class="myForms" id="1stform">
    <input type="text" value="1st Form" name="q1" />
</form>
<form action="http://www.google.com" method="get" class="myForms" id="2ndform">
    <input type="text" value="2nd Form" name="q2" />
</form>
<form action="http://www.google.com" method="get" class="myForms" id="3rdform">
    <input type="text" value="3rd Form" name="q3" />
</form>
<input type="button" id="clickMe" value="Submit ALL" />

jQuery:

Copy$('.myForms').submit(function () {
    console.log("");
    return true;
})

$("#clickMe").click(function () {
    $(".myForms").trigger('submit'); // should show 3 alerts (one for each form submission)
});
🌐
DEV Community
dev.to › zaxwebs › validating-multiple-forms-on-a-page-in-laravel-8-6l
Validating Multiple Forms on a Page in Laravel 8 - DEV Community
February 9, 2021 - In this post, I'd like to explain my process of handling & validating multiple forms that can have same-named fields. For example, you can have two side by side forms, say, login and signup on the same page. And you are likely to have matching fields like username, password, and such.
🌐
HashBangCode
hashbangcode.com › article › multi-page-forms-php
Multi Page Forms In PHP | #! code
Multi pages forms are just as they sound, a single form spread across multiple pages. These are useful in terms of usability as it can break up an otherwise dauntingly big form into smaller chunks. It can also be useful if you want to process some of the results in order to determine what forms the user sees on later steps. There are two ways in which it is possible to do this using PHP.
Top answer
1 of 4
7

Without some Javascript hocus-pocus, you can't. One form = one request.

You can do it with JS, and you have a few options. The easiest would be to loop through all the forms on the page, and basically duplicate all the input fields and values into one form and then submit that combined form.

With jQuery it'd go something like this:

$("form").submit(function() {
    combineAndSendForms();
    return false;        // prevent default action
});

function combineAndSendForms() {
    var $newForm = $("<form></form>")    // our new form.
        .attr({method : "POST", action : ""}) // customise as required
    ;
    $(":input:not(:submit, :button)").each(function() {  // grab all the useful inputs
        $newForm.append($("<input type=\"hidden\" />")   // create a new hidden field
            .attr('name', this.name)   // with the same name (watch out for duplicates!)
            .val($(this).val())        // and the same value
        );
    });
    $newForm
        .appendTo(document.body)  // not sure if this is needed?
        .submit()                 // submit the form
    ;
}
2 of 4
2

You need to make a script which will collect the data from the forms, and inject them into the only form that is visible. Only one form will be submitted, you can not submit multiple forms. You can create multiple hidden fields, or you can construct a single hidden field in that form, then use javascript to collect all the data from the various forms, then create a JSON string, set the value of the hidden one, and submit.

Edit: Say you have a single hidden input like this:

<input type='hidden' name='hiddenfield' id='hiddenfield' />

you could use JQuery to do this:

$('#hiddenfield').val('myvalue');

To get the value from other forms is as simple as calling $('#elementid').val()

before form submission. To use JQuery, go to the jquery website, download the library, and link it (follow their installation guide).

Top answer
1 of 3
1

You can use ajax.

form.php

<?php if(isset($_POST['step1'])&&isset($_POST['step2'])&&isset($_POST['step3'])){
  echo "You chose " . $_POST['step1']." and ".$_POST['step2']." and ".$_POST['step3'].". Well done.";die;
}?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"0"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Data form</title>
</head>
<script>
$(document).ready(function(){
    $("a.btn").click(function(){
        var datastring = $("#form1").serialize();
        datastring +="&" + $("#form2").serialize();
        datastring +="&" + $("#form3").serialize();
        $.ajax({
            type: "POST",
            url: "form.php",
            data: datastring,
            success: function(data) {
                console.log(data);
                alert(data);
            },
            error: function() {
                alert('error handing here');
            }
        });
    });
});

</script>
<body>
<form id="form1">
 <input name="step1" value="1" type="text"/>
</form>
<form id="form2">
 <input name="step2" value="2" type="text"/>
</form>
<form id="form3">
 <input name="step3" value="3" type="text"/>
</form>
 <a class="btn btn-success">Submit All</a>
</body>
</html>
2 of 3
0
$_POST['step2']

You don't have any fields with the name 'step2' on your form. Try changing it to 'step1'or change the names of fields in your second form.