为什么我的表单在刷新后会两次发送数据?

时间:2011-12-18 17:36:52

标签: php html forms

我的网站上有一个表单,但我无法解决一个问题。当我在表单框中写入一些文本时,它会将数据发送到数据库。当我点击刷新时,页面再次将相同的数据发送到数据库。我的代码有什么问题?

<?php
if(isset($_POST['submit']))
{   
$err = array();

$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$uname = $_SESSION['uname'];
$date = "On " . date("F Y h:i:s A");

if (!isset($_SESSION['uname']))

$err[] = "You need to login";

else
{
if(empty($sub) && empty($msg))

$err[] = "All field required";

else
{
if(empty($sub))
$err[] = "Subject Requried";

if(empty($msg))
$err[] = "Message Requried";
 }
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red><b>$er</b></font>";
}
}
else
{
$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
echo "Discussion was submitted";
}
}   
}
?>

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"     
name="discussion">
<table width="240" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="width:230;"><b>Select your Discussion</b>&nbsp;&nbsp;
<select name="type">
<?php   
$sqld = mysql_query("SELECT * FROM distype");

while($row = mysql_fetch_assoc($sqld))
{
$d_id = $row['d_id'];
$diss = $row['type'];
echo "<option value='$diss'>$diss</option>";
}
?>

</select></td>
</tr>
<tr>
<td><b>Subject</b></td>
</tr>
<tr>
<td><input type="text" name="sub" value="" size="33" class=""/></td>
</tr>
<tr>
<td><b>Message</b></td>
</tr>
<tr>
<td><textarea cols="30" rows="3" name="msg" class=""></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit Form"><br>
<td></td>
</tr>
</table>

2 个答案:

答案 0 :(得分:1)

在成功提交表单时,您需要重新加载网址或将其重定向到某处,以防止用户将数据插入数据库。

$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
   header("Location: page.php?mode=success");
   //or
   header("Location: ".$_SERVER['REQUEST_URI']); //which will just reload the page
}

答案 1 :(得分:1)

问题是,您的代码在发送相同数据时将以相同的方式执行。你需要通过许多结构中的一个来防止双重插入:

  • 桌子上的唯一钥匙
  • 在会话中存储最后一篇文章的哈希值,如果它与存储的哈希值相同则拒绝发布
  • 将用户重定向到成功的不同页面,以便刷新不会导致相同的POST