Php 每次重新加载页面时都会插入数据
我创建了在数据库中插入数据的表单,但每次重新加载页面时,数据都会再次插入。 我使用unset($\u POST)来修复它,但它不修复 如何使它只插入一次Php 每次重新加载页面时都会插入数据,php,html,mysql,sql,Php,Html,Mysql,Sql,我创建了在数据库中插入数据的表单,但每次重新加载页面时,数据都会再次插入。 我使用unset($\u POST)来修复它,但它不修复 如何使它只插入一次 <form method="post" class="job"> <input type="text" placeholder=" course name" name="name" class="form-control input-lg"> <input type
<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将再次获得相同的值。
在检查查询是否成功的if语句中,添加以下行:
标题('Location:')代码>
如果希望用户再次返回同一位置,请编写:
header('Location:'.$\u SERVER['PHP_SELF'])代码>首先,我认为您应该理解PHP是无状态的,每次调用脚本时,它都不会考虑以前的操作,例如POST数组的unset,这意味着unset($\u POST)
是无用的
您的问题是每次重新加载页面时,$\u POST['addcourse']
总是被设置。
我建议将此if(isset($\u POST['addcourse']){
更改为if(!empty($\u POST['name']){
,这意味着只有在设置了名称字段且名称不为空时才会执行查询
您还应该使用mysqli函数和prepared语句来防止像这样的sql注入。请不要在php中使用mysql函数。它们从5.6开始就被弃用,并且不安全。Furhter在php7中被删除。请改用mysqli或PDO。您的代码有sql注入的风险!我是初学者,所以我不知道如何保护我的代码rom SQL注入或如何使用PDO。我仍然非常了解数据库,问题已经解决,但为什么echo“alert('insert successful');”变得不起作用非常感谢,我可以说这是我的第二个代码,所以我不知道很多事情,但现在我将学习如何使用mysqli函数和准备好的语句来防止SQL注入,再次感谢