数据库中有一个名为 temp1 的用户表。
用户有两列:姓名和姓氏。
名字和姓氏是通过表格输入的。数据已成功输入数据库。但我注意到,如果您重新加载页面并接受重新提交表单,那么数据会再次输入数据库。
网站可以接受这种行为吗?这被认为是一个错误吗?如何解决?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style rel="stylesheet">
label {
width: 150px;
}
.input-area {
margin-bottom: 15px;
}
</style>
</head>
<body>
<form action="" method="POST">
<div class="input-area">
<label>Имя</label>
<input type="text" name="name">
</div>
<div class="input-area">
<label>Фамилия</label>
<input type="text" name="surname">
</div>
<div class="input-area">
<input type="submit" value="Занести данные в базу">
</div>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$pdo = new PDO("mysql:host=localhost;dbname=temp1", "root", "");
$name = htmlentities(trim($_POST["name"]));
$surname = htmlentities(trim($_POST["surname"]));
$stmt = $pdo->prepare("INSERT INTO users(name, surname) VALUES(?, ?)");
$stmt->execute([$name, $surname]);
?>
</body>
</html>