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

标签 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>";}
}
?>

最佳答案

首先,我认为您应该了解 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/

相关文章:

javascript - Onclick 使用 JavaScript 更改下拉列表的宽度

javascript - 使用 AJAX 检索的 UTF 字符未在 Safari 中显示

mysql - 在一个查询中使用两个具有不同属性的数据库

php - 将 stdout 和 stderr 重定向到同一管道

带有 SQL 语法的 PHP 简单文本数据库

php - 查找与多个类别相关的视频 (1 :N Relation) mysql

php - 升级到 laravel 5.8 后数据库访问错误

html - 输入选择框不要在 Safari 中使用填充

php - 产品具有属性(变体)数据库设计?

mysql - 从巨大的表中删除大量数据