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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)