2014-09-25 49 views
0

当我提交一个form.php它调用insert.php。 insert.php将表单数据插入到数据库中,并回显“成功添加记录”消息。我希望在显示此消息后,自动调用返回到form.php。我还评论了我必须重定向的行。 想要自动重定向到一些页面在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); 
 
?>

+1

您可以使用标题,但是您也将无法回显消息,因为这将在标题之前输出。如果你想同时回声和重定向,你将需要使用JS或元刷新。 – 2014-09-25 08:00:40

回答

0

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

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

例子:

header("Location: form.php"); 
+0

谢谢!非常好回答 – 2014-09-25 08:40:15

1

可以使用头功能做到这一点:

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

页面将在10秒钟内重定向。

+0

谢谢!很好的答案! – 2014-09-25 08:39:20

0

添加到凯文关于使用位置的评论。我有一个网站建立了这个,我将消息从'control'(你的案例中的insert.php)传递给'View'(你的案例中的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的消息的类。