I have a problem with my php code. I have 2 html forms, and I need to display the input data in inputs after the user submits the each forms. I have a problem, where user submits form 1 the data is correctly displayed in the form, but when the user submits form 2 the data from form 1 gets erased, and I want both forms to display the input data. Below is simplified code for demonstration.
<?php
$name1 = "";
$email1 = "";
$name2 = "";
$email2 = "";
?>
<?php
if (isset($_POST['submit1'])) {
$name1 = $_POST['name1'];
$email1 = $_POST['email1'];
}
if (isset($_POST['submit2'])) {
$name2 = $_POST['name2'];
$email2 = $_POST['email2'];
}
?>
<form action="index.php" method="post">
Name: <input type="text" name="name1" value="<?php echo $name1; ?>"><br>
E-mail: <input type="text" name="email1" value="<?php echo $email1; ?>"><br>
<input type="submit" value="send" name="submit1">
</form>
<form action="index.php" method="post">
Name: <input type="text" name="name2" value="<?php echo $name2; ?>"><br>
E-mail: <input type="text" name="email2" value="<?php echo $email2; ?>"><br>
<input type="submit" value="send" name="submit2">
</form>
CodePudding user response:
You can use PHP sessions. When a form on the page is submitted you can store the $_POST variables in the $_SESSION and then just the $_SESSION variables to fill in the form. See code below:
<?php
session_start(); //start the session
if(isset($_POST)){ //check to see if a form has been submitted
// merge the $_SESSION & $_POST arrays,
// this will overwrite session variables with new post variables but keep old post variables that haven't been submitted
$_SESSION = array_merge($_SESSION,$_POST);
}
$name1 = "";
$email1 = "";
$name2 = "";
$email2 = "";
?>
<?php
if (isset($_SESSION['submit1'])) { //uses $_SESSION instead of $_POST
$name1 = $_SESSION['name1'];
$email1 = $_SESSION['email1'];
}
if (isset($_SESSION['submit2'])) { //uses $_SESSION instead of $_POST
$name2 = $_SESSION['name2'];
$email2 = $_SESSION['email2'];
}
?>
<form action="index.php" method="post">
Name: <input type="text" name="name1" value="<?php echo $name1; ?>"><br>
E-mail: <input type="text" name="email1" value="<?php echo $email1; ?>"><br>
<input type="submit" value="send" name="submit1">
</form>
<form action="index.php" method="post">
Name: <input type="text" name="name2" value="<?php echo $name2; ?>"><br>
E-mail: <input type="text" name="email2" value="<?php echo $email2; ?>"><br>
<input type="submit" value="send" name="submit2">
</form>
If you have any questions let me know.
CodePudding user response:
each request to server will run independetly
so you need to store data from 1st form in some way until user send second form
- Easyest - render input data as hidden fields in 2nd form. Something like :
<input type="hidden" name="name1" value="<?php echo $_POST['name1']; ?>">
2. Store data between form submits in database or cookie