douyalin2258 2017-02-12 04:05
浏览 51
已采纳

使用表单POST多个会话变量,在后续页面上输出

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.

  • 写回答

1条回答 默认 最新

  • dpb35161 2017-02-12 04:10
    关注

    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;?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致