数据插入每次重新加载页面

时间:2017-11-13 16:06:49

标签: php html mysql sql

我创建了在数据库中插入数据的表单,但每次重新加载页面时,数据都会重新插入。 我使用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>";}
}
?>

2 个答案:

答案 0 :(得分:1)

首先,我认为您应该了解PHP是无状态的,每次调用脚本时,它都不会考虑以前的操作,例如POST数组的未设置,这意味着unset($_POST)是无用的。

您的问题是,每次重新加载页面时,始终会设置$_POST['addcourse']。 我建议使用此if (isset($_POST['addcourse'])){更改此if (!empty($_POST['name'])){,这意味着只有在设置了名称字段且名称不为空时才会执行查询。

您还应该使用mysqli函数和预处理语句来阻止sql注入,就像在example中一样。

答案 1 :(得分:0)

由于请求仍包含所有值,因此刷新时,Php将再次获得相同的值。 在if语句中,检查查询是否成功,添加以下行:

container

如果您希望用户再次结束同一个地方,请写下:

header('Location: <where you want the user to be sent to>');

相关问题