在页面刷新时自动插入先前插入的值

brc7rcf0  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(275)

通过php通过html表单在数据库中插入值的查询或解决方案是什么,但是每次我刷新页面时,前面插入的值会再次被插入?

if (isset($_POST["insert1"])) { 
    $inrtno = $_POST["inrouteno"];
    $instp = $_POST["instop"];

    if ($inrtno !=''||$instp !='') {
        $query = mysqli_query($datacon,"REPLACE INTO `stops`(`sn`, `routeno`, `stop`) VALUES ('NULL','$inrtno','$instp')");
        echo "<script type='text/javascript'>alert('Insertion Successful !!!')</script>";
    } else {
        echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";   
    }
}
b1uwtaje

b1uwtaje1#

如前所述(我个人理解),每次刷新页面时,都会再次发送请求。请注意,我忘了,谢谢你@adyson。
因此,一个解决方案是在插入之后将用户重定向到相同的表单。
假设此文件为test.php,例如:

if (isset($_POST["insert1"])) { 
    $inrtno = $_POST["inrouteno"];
    $instp = $_POST["instop"];

    if ($inrtno !=''||$instp !='') {
        $query = mysqli_query($datacon,"REPLACE INTO `stops`(`sn`, `routeno`, `stop`) VALUES ('NULL','$inrtno','$instp')");
        echo "<script type='text/javascript'>alert('Insertion Successful !!!')</script>";

        sleep('3');
        header('Location: /test.php');
        exit();
    } else {
        echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";   
    }
}
wfauudbj

wfauudbj2#

重新加载页面时,浏览器会要求您重新提交请求,因此值会再次传输。因此,在插入数据时设置一个条件,以检查记录是否已经存在。

iyfamqjs

iyfamqjs3#

每当您刷新页面时,您都在重新提交post变量,因此php仍然运行。此外,您的查询还有sql注入的危险。考虑使用pdo。

相关问题