【问题标题】:Want to redirect to some page automatically in php想在php中自动重定向到某个页面
【发布时间】:2014-09-25 07:58:08
【问题描述】:

当我提交 form.php 时,它会调用 insert.php。并 insert.php 在数据库中插入表单数据并回显消息“记录成功添加。”。我希望在显示此消息后自动检索到 form.php。我还评论了我必须重定向的行。

My form.php

    <html>
<body>

<form action="insert.php" method="post">
Name: <input type="text" name="myname"><br>
Comment: <input type="text" name="mycomment"><br>
<input type="submit">
</form>

</body>
</html>

My insert.php

    <?php
$con=mysqli_connect("localhost","root","","commentdb");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['myname']);
$lastname = mysqli_real_escape_string($con, $_POST['mycomment']);


$sql="INSERT INTO person (Name, Comment, Time)
VALUES ('$firstname', '$lastname', NOW())";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

echo "1 record added";
// Here it should retrieve
mysqli_close($con);
?>

【问题讨论】:

  • 您可以使用标头,但您也不能回显消息,因为这将在标头之前输出。如果你想要回显和重定向,你将需要使用 JS 或元刷新。

标签: php


【解决方案1】:

你可以使用 header 函数来做到这一点:

header( "refresh:10;url=form.php" );

页面将在 10 秒后重定向。

【讨论】:

    【解决方案2】:

    您可以使用 Location 标头使用 PHP 重定向到另一个页面。

    小心删除标题之前的任何回声。输出开始后您不能使用header()(如果您打算重定向访问者,这无用)。

    例子:

    header("Location: form.php");
    

    【讨论】:

    • 谢谢!很好的答案
    【解决方案3】:

    添加到凯文关于位置使用的评论。我有一个用这个构建的网站,我将消息从“控件”(在您的情况下为 insert.php)传递到“视图”(在您的情况下为 form.php)。

    在“控制”中,我用消息设置了一个会话变量,例如:

                $_SESSION["mess"] = "BOOK0015";
    

    然后使用:

    header ("Location:UIATbooks.php?id=".$authorid)
    

    回到我的“视图”。

    在“视图”中,我查找消息并显示,例如:

    if (isset($_SESSION['mess'])) {
        $mess = $_SESSION['mess'];
      }
      else {
        $mess = "";
      }
      if ($mess != "") {
        $objmess = new clsmessage ();
        echo '<p><span class="style3">'.$objmess->returnmess ($objscreen->connection,$mess).'</span></p>';
        unset($_SESSION['mess']);
      }
    
    $objscreen->endscreen ();
    

    我有一个基于 ID 存储消息的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多