我创建了在数据库中插入数据的表单,但每次我重新加载页面时,数据都会再次插入。 我使用 unset($_POST) 来修复它,但它没有修复。
如何让它只插入一次。
<form method="post" class="job">
<input type="text" placeholder=" course name" name="name" class="form-control input-lg">
<input type="text" placeholder=" country " name="country" class="form-control input-lg">
<input type="text" placeholder=" company " name="company" class="form-control input-lg">
<input type="date" placeholder=" start " name="start" class="form-control input-lg">
<input type="date" placeholder=" end " name="end" class="form-control input-lg">
<input type="text" placeholder="link" name="link" class="form-control input-lg">
<button type="submit" class="btn btn-warning btn-lg btn-block" name="addcourse" id="addcourse"> ADD COURSE </button>
</form>
</div>
<div class="col-lg-4"></div>
</div>
<?php
include("connect.php");
if (isset($_POST['addcourse'])){
$name = $_POST["name"];
$country = $_POST["country"];
$company = $_POST["company"];
$link = $_POST["link"];
$start=$_POST["start"];
$end=$_POST["end"];
$newcourse="INSERT INTO courses (name,country,company,start,end,link) VALUES ('$name','$country','$company','$start','$end','$link')";
if(!empty($name)&&!empty($country)&&!empty($company)&&!empty($link)&&!empty($start)&&!empty($end)){
if(mysql_query($newcourse)){
unset($_POST);
echo "<script> alert('insert successful'); </script>";
}
else{ unset($_POST);
echo "<script>alert('error'); </script>";
}}
else { unset($_POST);
echo "<script>alert('fill in all field'); </script>";}
}
?>
最佳答案
首先,我认为您应该了解 PHP 是无状态的,每次调用脚本时,它都不会考虑之前的操作,例如 POST 数组的 unset,这意味着 unset($_POST)
没用。
您的问题是每次您重新加载页面时,$_POST['addcourse']
总是被设置。
我建议将此 if (isset($_POST['addcourse'])){
更改为此 if (!empty($_POST['name'])){
这意味着只有在设置了名称字段并且名称不为空时才会执行查询。
您还应该使用 mysqli 函数和准备好的语句来防止像这 example 中的 sql 注入(inject).
关于php - 数据插入每次重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47268616/