user257735
user257735

Reputation: 21

Store values from multiple form in $_POST

I am trying to store values from multiple forms in the $_POST variable. The forms are on different pages and from what I can understand from the test I did, when I submit values from a form, they "overwrite" the values that where already in $_POST.

Here is an example of what I am trying to do :

Page 1 - form 1

<?php 
session_start();
?>

<form method="post" action="page2.php">
First name : <input type="text" name="firstName" required ><br/><br/>
Last name : <input type="text" name="lastName" required ><br/><br/>
<input type="submit">
</form>

Page 2 - form 2

<?php 
session_start();
?>

<form method="post" action="page3.php">
Age : <input type="text" name="age" required ><br/><br/>
City : <input type="text" name="city" required ><br/><br/>
<input type="submit">
</form>

Page 3 - results

<?php 
session_start();

echo $_POST['firstName'].'<br/>';
echo $_POST['lastName'].'<br/>';
echo $_POST['age'].'<br/>';
echo $_POST['city'].'<br/>';
?>

The last page shows me only 'age' and 'city'. The values from the first form on page 1 are now undefined. Here is the an example of the result I get :

Notice: Undefined index: firstName on line 4

Notice: Undefined index: lastName on line 5

65
New York

Upvotes: 0

Views: 519

Answers (3)

Jay Bhatt
Jay Bhatt

Reputation: 5651

You can also use session variables like this:

//Page 1

<?php
      session_start();
      $_SESSION['user'] = array();
      $_SESSION['user']['firstName'] = $_POST['firstName'];
      $_SESSION['user']['lastName'] = $_POST['lastName'];
?>

//Page 2

<?php
      session_start();
      $_SESSION['user']['age'] = $_POST['age'];
      $_SESSION['user']['city'] = $_POST['city'];
?>

//Result

<?php
          session_start();
          echo $_SESSION['user']['firstName'];
          echo $_SESSION['user']['lastName'];
          echo $_SESSION['user']['city'];
          echo $_SESSION['user']['age'];
    ?>

Upvotes: 1

ɹɐqʞɐ zoɹǝɟ
ɹɐqʞɐ zoɹǝɟ

Reputation: 4370

in page2.php put this

<input type="hidden" name="firstname" value="<?=$_POST['firstname']?>">
<input type="hidden" name="lastname" value="<?=$_POST['lastname']?>">

Upvotes: 4

Jenz
Jenz

Reputation: 8369

As I can see in the code above, you are trying to post the data to two different files.

<form method="post" action="page2.php">

This has action page as page2.php.

<form method="post" action="page3.php">

Here you are submitting data to page3.php

And you are trying to access

echo $_POST['firstName'].'<br/>';
echo $_POST['lastName'].'<br/>';

in page3.php which you have passed to page2.php. Definitely this won't work as you can access the values submitted through a form in the action page of the form only.

Upvotes: 0

Related Questions