PHP插入重复在DBPHP插入重复在DB(PHP Inserting Duplicates In D

2019-05-12 12:41发布

我'试图建立一个注册页面和当前的代码运行正常,但我'在DB侧发现了重复的插件。 我已经研究和尝试了好几种不同的解决方案,但没有尚未制定。 我希望它很简单的说我'失去了一些东西。 我怎样才能阻止我当前的代码从插入两次?

<?php
session_start();
$error=''; // Variable To Store Error Message
if (isset($_POST['register'])) {
//if (empty($_POST['email']) || empty($_POST['hash'])) {
//$error = "<br /> <p style='font-family:talo; color:red; margin-top:10px; font-size:16px;'>* Username or Password is invalid</p>";
//}
//else
//{
// Define all labels on the register form
$firstName=$_POST['firstName'];
$lastName=$_POST['lastName'];
$title=$_POST['title'];
$suffix=$_POST['suffixOne'];
$suffixTwo=$_POST['suffixTwo'];
$email=$_POST['email'];
$employer=$_POST['employer'];
$expertise=$_POST['expertise'];
$hash=$_POST['password'];
$confirmHash=$_POST['passwordConfirm'];
$primaryAddress=$_POST['primaryAddress'];
$secondaryAddress=$_POST['secondaryAddress'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$country=$_POST['country'];
$primaryPhone=$_POST['primaryPhone'];
$secondaryPhone=$_POST['secondaryPhone'];

$connection = mysqli_connect("localhost", "username", "password","DB");


$register = "INSERT INTO user (userID, firstName, lastName, title, suffix, suffixTwo, email, employer, expertise, primaryAddress, secondaryAddress, primaryPhone, secondaryPhone, city, postalCode, hash) 
VALUES (DEFAULT, '$firstName', '$lastName', '$title', '$suffix', '$suffixTwo', '$email', '$employer', '$expertise', '$primaryAddress', '$secondaryAddress', '$primaryPhone', '$secondaryPhone', '$city', '$zip', '$hash')";
if (mysqli_query($connection, $register)) {
   header('Location: index.php');
}
mysqli_close($connection);
}
?>

Answer 1:

如果页面被刷新,或再次使用“后退”按钮有人点击,数据将得到重新发送到服务器,从而获得两次插入。 您需要将用户重定向到另一个页面,或在同一个页面,使用POST /重定向/ GET模式来避免这种情况。 发送303 HTTP响应会告诉浏览器替换页面在其历史上,从而避免重复发送发布的数据。

if (mysqli_query($connection, $register)) {
    header('Location: index.php', true, 303);
    exit;
}


文章来源: PHP Inserting Duplicates In DB