【问题标题】:Changes occur only on refresh after re-direct on posting a form a php仅在重新发布表单 php 后刷新时才会发生更改
【发布时间】:2013-02-22 17:22:33
【问题描述】:

我有一个用户发布表单的页面。它在php

如果用户已经登录,则不会显示该表单。 如果用户未登录,则会显示该表单。

现在,当用户首次访问该网站时,会显示该表单。然后他填写表格并将submits 填写为POST。成功登录后,他将被重定向到同一页面。

问题是,重定向到同一页面后,表单仍然可见。但是,如果我刷新它,表单就会消失。

如何更改/修改以实现我想要的。

我不知道提供我的代码是否会有所帮助。不过,根据 SO,我附上了我的基本代码:

    if(!isset($_SESSION['id'])){
    //show form
    <form action="" method="post">
        <br><button class="lfloat" type="submit" id="submit" value="register0" name="submit">Register</button><br><br>
    </form>
    <?php if(isset($_POST['submit'])&&$_POST['submit']=='register0'){
        //do all the insertion of data into database here only.
        ....
        ....
        echo "Success!!";
    }
}
if(isset($_SESSION['id'])){
    //don't show form

}

【问题讨论】:

  • 你在代码的什么地方设置了 $_SESSION['id'] ?
  • @John:在页面的开头我已经包含:session_start();
  • 是的,但是你在哪里设置 $_SESSION['id'] ?表格发布后?你能把它包含在你的示例代码中吗?

标签: php forms session post


【解决方案1】:

类似

 if(isset($_POST['submit'])&&$_POST['submit']=='register0'){
        //do all the insertion of data into database here only.
        ....
        ....
        echo "Success!!";
$_SESSION['id'] = 'some value';
header(Location: 'yourForm.php');
exit;

    }

应该为你工作......也不要忘记写

session_start();

在 form.php 的顶部

【讨论】:

    【解决方案2】:

    这就是我的做法:

    <?php $hideForm = isset($_SESSION['id']); ?>
    
    <form action="" method="post" style="<?= $hideForm ? 'display:none;' : '' ?>" >
    ...
    

    或者更简洁:

    <form action="" method="post" style="<?= isset($_SESSION['id']) ? 'display:none;' : '' ?>" >
    

    【讨论】:

      【解决方案3】:

      嗯,确实你在数据库中保存了ID,但是我没有看到你重新加载页面,所以在你保存ID之后SESSION中就不存在了。

      您可以在保存新信息后执行&lt;form action="pageURL.php?action=save"&gt;,但也许您需要进行切换并通过查询字符串传递一个操作,以便帖子不会在刷新时重新提交。我们的想法是使用这种模式:Post/Redirect/Get。然后您的页面将如下所示:

      $action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
      
      switch ($action) {
          case 'save':
              //Do your the registration and then
              header('Location:YourPagePath.php?action=saved');
              break;
          case 'save':
              /*FALL TRHOUGH*/
          default:
              //The rest of the page code
              break;
      }
      

      此外,在成功登录后,快速但不是那么好的解决方案是:

      echo '<script>
          alert("Save successful");
          location.href="YourPagePath.php"
      </script>';
      exit;
      

      【讨论】:

        猜你喜欢
        • 2016-11-27
        • 2011-09-11
        • 1970-01-01
        • 2016-12-29
        • 2012-12-17
        • 2012-11-05
        • 1970-01-01
        • 2012-07-04
        • 1970-01-01
        相关资源
        最近更新 更多