Faye
Faye

Reputation: 134

POST multiple session variables with form, output on subsequent pages

I've been through 20 or so different posts and I can't seem to get this right piecing together questions and answers for different aspects of what I'm trying to accomplish.

I have a form the user can fill out. I want that upon submitting the form, the choices made will be used as variables throughout the rest of the website.

My code:

<form action="page1" method="POST">
  <input type="text" name="var_1">
  <input type="text" name="var_2">
  <input type="submit" value="Submit" class="submit" name="submit">
</form>


<?php

session_start();

 if (isset($_POST['submit'])) {

   $_SESSION['var_1'] = $_POST['var_1'];
   $_SESSION['var_2'] = $_POST['var_2'];

 }
?>

Next Page:

<?php

session_start();

$var_1 = $_SESSION['var_1'];
$var_2 = $_SESSION['var_2'];

?>

<?php echo $var_1';?>
<?php echo $var_2';?>

This results in blank echos and a repeated error for each variable at the top of the page:

Notice: Undefined index: var_1 in page1.php on line #

Obviously my sessions aren't making it the second page, but I don't know why or what I've done wrong. This has been pieced together from posts about adding multiple sessions, posting sessions, getting sessions.

Upvotes: 1

Views: 955

Answers (1)

affaz
affaz

Reputation: 1191

Either Remove the action from your <form> and give the redirect to page1 in the PHP code because the PHP code below wont work and get redirected to the next page.As a result of which the session will not be set

    <form action="" method="POST">
      <input type="text" name="var_1">
      <input type="text" name="var_2">
      <input type="submit" value="Submit" class="submit" name="submit">
    </form>
    <?php

 session_start();

 if (isset($_POST['submit'])) {

   $_SESSION['var_1'] = $_POST['var_1'];
   $_SESSION['var_2'] = $_POST['var_2'];
   //redirect
   header("Location: page1.php");
 }
?>

Or set the session in the next page without the code below

<form action="page1" method="POST">
  <input type="text" name="var_1">
  <input type="text" name="var_2">
  <input type="submit" value="Submit" class="submit" name="submit">
</form>

page1.php

<?php

session_start();
$_SESSION['var_1'] = $_POST['var_1'];
$_SESSION['var_2'] = $_POST['var_2'];
$var_1 = $_SESSION['var_1'];
$var_2 = $_SESSION['var_2'];

?>

<?php echo $var_1;?>
<?php echo $var_2;?>

Upvotes: 3

Related Questions