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 OverflowIt'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
}
}
create separate form_process script then include in form pages.
if(!empty($_POST)){
include 'form_process.php';
}
form_process.php should contain only class/function without echo or print out.
alternately you may set action url to the same page then redirect back to proper page.
<form id="add-profile-form" action="form_controller.php" method="post">
<input type="hidden" name="act" value="adding"/>
<!-- form 1. -->
</form>
<form id="edit-profile-form" action="form_controller.php">
<input type="hidden" name="act" value="editing"/>
<!-- form 2. -->
</form>
form_controller.php
if(isset($_POST['act']){
if($_POST['act'] == 'adding'){
//process form1
}else if($_POST['act'] == 'editing'){
//process form2
}
header("Location: success.php");
}
html - How to process multiple forms using one php script - Stack Overflow
Multiple Forms on One Page - PHP - SitePoint Forums | Web Development & Design Community
html - How to handle multiple php forms using one php page - Stack Overflow
Handling multiple forms across a website in PHP
Videos
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.
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
}
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
)
Consider using isset() to check for a specific variable. It can be better then checking with empty().
<!DOCTYPE html>
<html>
<head>
<title>PHP demo</title>
</head>
<body>
<?php
if(isset($_POST['form1'])){
echo "<h1>student information</h1>\r\n";
echo "title is : $_POST['pullDownMenu']<br />\r\n";
echo "first name is : $_POST['firstname']<br />\r\n";
echo "lastname is : $_POST['lastname']\r\n";
}
if (isset($_POST['form2'])) {
echo "<p>Following details are saved to database</p>\r\n";
echo "reg No\t:\t$_POST['RegNO']<br />\r\n";
echo "NIC\t:\t$_POST['NIC']<br />\r\n";
echo "Tel No\t:\t$_POST['Telephone']<br />\r\n";
}
?>
</body>
</html>
If you have more forms, consider using switch() instead of if().
You could set different values for button submit for each form. Or you could use a input tag hidden to set type of form. Example:
Form1 : <input type="hidden" name="type" value="form1">
Form2 : <input type="hidden" name="type" value="form2">
And in php form
if($_POST["type"]=="form1")
{
//code here
}else if($_POST["type"]=="form2"){
//code here
}
You could make two forms with 2 different actions
<form action="login.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<br />
<form action="register.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="submit" value="Register">
</form>
Or do this
<form action="doStuff.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="hidden" name="action" value="login">
<input type="submit" value="Login">
</form>
<br />
<form action="doStuff.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="hidden" name="action" value="register">
<input type="submit" value="Register">
</form>
Then you PHP file would work as a switch($_POST['action']) ... furthermore, they can't click on both links at the same time or make a simultaneous request, each submit is a separate request.
Your PHP would then go on with the switch logic or have different php files doing a login procedure then a registration procedure
Well you can have each form go to to a different page. (which is preferable)
Or have a different value for the a certain input and base posts on that:
switch($_POST['submit']) {
case 'login':
//...
break;
case 'register':
//...
break;
}
If you want the action to be read as POST, try putting it in a hidden input instead. One of your forms would look like this:
<form action="editmenusprocess.php" method="POST">
<legend><h3 style="margin-top: 20px;">Add Starter</h3></legend>
<div class="form-group">
<label for="exampleInputEmail1">Food:</label>
<input type="text" class="form-control form-control-lg" name="msfood" placeholder="Title">
<input type="hidden" name="action" value="starter">
</div>
<!-- THE REST OF THE INPUT FIELDS BELOW -->
Do the rest to your other forms.
Then, in your editmenusprocess.php:
$action = (!empty($_POST["action"]))?$_POST["action"]:null;
if($action == 'starter'){
$stmt = $link->prepare("INSERT INTO 2043menustarter (food, descript, price) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $_POST["msfood"], $_POST["msdescript"], $_POST["msprice"]);
$stmt->execute();
$stmt->close();
}
/*** THEN THE REST OF YOUR OTHER CONDITIONS BELOW ***/
In the comment section of your post, people have been suggesting that you at least use prepared statement. You can read more about it here.
The action value is encoded in the query string.
PHP parses the query string into the $_GET superglobal. Only data from the request body will be parsed into the $_POST superglobal.
Use $_GET['action'] or move the data from the query string to an input.
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.
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
}
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)
});
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
;
}
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).
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>
$_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.