2014-09-25 47 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的消息的類。