2011-07-06 41 views
0

我的PHP表單有問題。每當我刷新頁面時,舊數據都會自動插入到我的數據庫中。我的代碼是:刷新表單 - >上傳數據

<?php 
    if(isset($_GET['send'])){ 
     isset($_GET['name'])?$name = $_GET['name']:""; 
     isset($_GET['score'])?$score = $_GET['score']:0; 

     $con = mysql_connect('localhost','root','') or die(mysql_error()); 
      mysql_select-db('student',$con) or die(mysql_error()); 
     $qry = mysql_query('INSERT INTO student(name, score) VALUES('$name', $score)') or die(mysql_error()); 

     $display = mysql_query('SELECT * FROM student',$con) or die(mysql_error()); 
     echo '<table border=1>'; 
     while($rows = mysql_fetch_array($display)){ 
      echo '<tr>'; 
      echo "<td>$rows['id']</td>"; 
      echo "<td>$rows['name']</td>"; 
      echo "<td>$rows['score']</td>"; 
      echo '</tr>'; 
     } 
     echo '</table>'; 
    } 
    ?> 

請幫我解決這個問題。

+1

ofcourse ...您的插入查詢每次執行刷新它。
嘗試使它,如果某個條件滿足..執行插入查詢...嘗試將它放入一個if。 – rrapuya

+0

你必須檢查你的提交。我想。 http://www.webmaster-forums.net/web-programming-and-application-development/posting-php-self-stop-dublicate-insert-refresh – newbie

回答

2

防止重複表單提交的常用方法是使用Post/Redirect/Get Pattern

然後,您需要將表單方法更改爲。成功提交表單後,您將重定向到表單,但重定向請求。表單將被重置(空值)。

編輯:

現在,當我看到它,你的腳本實際上可以做同樣的事情:插入MySQL數據庫後,您可以將其重定向到它自身刪除的get參數:

<?php 
if(isset($_GET['send'])){ 
    isset($_GET['name'])?$name = $_GET['name']:""; 
    isset($_GET['score'])?$score = $_GET['score']:0; 

    $con = mysql_connect('localhost','root','') or die(mysql_error()); 
     mysql_select-db('student',$con) or die(mysql_error()); 
    $qry = mysql_query('INSERT INTO student(name, score) VALUES('$name', $score)') or die(mysql_error()); 
    header('Location: myscriptsurl.php'); 
    exit; 
} 

$display = mysql_query('SELECT * FROM student',$con) or die(mysql_error()); 
echo '<table border=1>'; 
while($rows = mysql_fetch_array($display)){ 
    echo '<tr>'; 
    echo "<td>$rows['id']</td>"; 
    echo "<td>$rows['name']</td>"; 
    echo "<td>$rows['score']</td>"; 
    echo '</tr>'; 
} 
echo '</table>'; 
?> 
+0

男人,這似乎是在另一個頁面顯示結果。但是,我的目的是在同一頁面插入並顯示結果 –

+0

@tepkenvannkorn:您需要將頁面鏈接放在那裏。因爲我不知道它,所以我在那裏放置了一個佔位符;) – hakre

+0

嗯,我試過了,但它仍然以另一個頁面顯示的方式 –

1

所以你有一個問題。從過程

<form action="process.php" method="POST"> 
<input type="text" name="number"> 
<input type="sumbit"> 
</form> 

則: 而且因爲你無法避免屏幕的刷新...

如果你正在做一個表格後,你可能會在你插入的記錄考慮發送位置 頭.PHP: //做數據庫您通常插入立足崗位

header("Location: http://www.example.com/thanks.php"); 
// do not forget the exit, since your script will run on without it. 
exit; 

這樣一來你的腳本將處理過帳,然後重定向 瀏覽器到thanks.php. 重載thanks.php不會導致新的數據庫插入。

1

U使用了GET方法,因此每次頁面刷新時都會從URL中獲取值。 嘗試使用POST方法...這將解決你的問題,不要忘記把條件POST

if(isset($_POST)) 
{ 
    /* Your Insert Code */ 

}