在表单提交后调用当前id


Recall the current id after form submission

我有一个允许用户通过编辑页面更新记录的数据库。提交编辑后,我希望浏览器自动返回到他们更新的页面以查看结果。我想过用JS来完成这个:

if(mysqli_query($con, $sql)){
    echo "<script> alert('You have successfully updated.');
            window.location.href='javascript:history.go(-2)';
          </script>";
 }else{
    echo "An error has occurred. Please go back and check the code: ".mysqli_error($con);
 }

,但这只会强制浏览器返回到该页面,而不是显示更改后的刷新页面。我需要手动刷新页面才能看到这样的结果。

我也试过:

if(mysqli_query($con, $sql)){
    echo "<script> alert('You have successfully updated.');
            window.location.href='01T.php?id=$id';
          </script>";
 }else{
    echo "An error has occurred. Please go back and check the code: ".mysqli_error($con);
 }

因为01T.php是显示信息的页面,但这不起作用。

如何将浏览器重定向到已编辑的相同id以查看结果,使用更合适的PHP解决方案?

使用header重定向

if(mysqli_query($con, $sql)){
    header("Location: [url]?id=$id");
 }else{
    echo "An error has occurred. Please go back and check the code: ".mysqli_error($con);
 }

我将使用PHP Sessions在页面之间保存消息,然后在加载新页面时检查消息是否存在。如果有,显示出来。

在您的示例中,如果查询成功运行,您将保存消息,然后重定向用户。然后,当新页面加载时,检索该消息并显示它。

<?php
session_start();
...
if(mysqli_query($con, $sql)){
    $_SESSION['message'] = "success";
    header("Location: 01T.php?id=$id");
    exit;
}else{
    echo "error";
}

然后在您想要显示消息的每个页面:

<?php
session_start();
$msgHtml = null; //if it stays null, no message will be shown
//if there is a message. Capture it, then clear it from the session
if(!empty($_SESSION['message'])){
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
    //Build the content you want the user to see. Add CSS classes to style it
    $msgHtml = "<div>$message</div>"
}

现在,如果有给用户的消息,显示它。如果没有消息,将不输出任何内容。

PHP:

echo $msgHtml;

或者在HTML中:

<body>
    <?= $msgHtml ?>
</body>