【发布时间】:2014-03-22 14:10:10
【问题描述】:
如果我通过 PHP 向数据库中插入一条新记录,然后单击提交按钮,然后每次刷新页面时,它都会将最近添加的记录插入数据库中。我该如何阻止这种情况发生?我也不想在提交按钮之后重定向到另一个表单。奇怪的是,如果我单击提交按钮两次,然后刷新表单,它不会将重复项插入数据库。为什么是这样?请帮忙:/谢谢
代码如下:
<div class="insertDiv">
<form method="POST" action="contracts.php">
<?php
if(empty($_POST['ContractDate']) && empty($_POST['ComputerId2']) && empty($_POST['CustomerId']) && empty($_POST['ContractLevel']))
{
}
else
{
include("dbinfo.inc.php");
$comm=@mysql_connect(localhost,$username,$password);
$rs=@mysql_select_db($database) or die( "Unable to select database");
$contractDate=$_POST['ContractDate'];
$computerID=$_POST['ComputerId'];
$customerID=$_POST['CustomerId'];
$contractLevel=$_POST['ContractLevel'];
$sql="INSERT INTO contract VALUES ('','$contractDate','$computerID', '$customerID', '$contractLevel')";
$result=mysql_query($sql)or die("Insert Error: ".mysql_error());
mysql_close();
}
?>
<div class = "myButton">
Insert
</div>
<p></p>
Enter contract start date: 
<input type="date" name="ContractDate" size=30 class="input"><br><br>
Enter computerID: 
<input type="text" name="ComputerId" size=30 class="input"><br><br>
Enter customerID: 
<input type="text" name="CustomerId" size=30 class="input"><br><br>
Enter contract level: 
<input type="text" name="ContractLevel" size=30 class="input"><br><br>
<input type="reset" value="Reset" class="button">    
<input type="submit" value="Submit" class="button">
</form>
</div>
【问题讨论】:
-
您的代码容易受到 SQL 注入的攻击。你应该阅读how to prevent them in PHP。