首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP在DB中插入重复项

PHP在DB中插入重复项
EN

Stack Overflow用户
提问于 2016-02-26 01:08:44
回答 1查看 140关注 0票数 0

我正在尝试构建一个注册页,并且当前代码运行正常,但是我在DB端得到了重复的插入。我已经研究并尝试过几种不同的解决方案,但还没有结果。我希望这是一件很简单的事情,我错过了。如何防止我的当前代码插入两次?

代码语言:javascript
运行
复制
<?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);
}
?>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-26 01:14:17

如果页面被刷新,或者有人再次使用“后退”按钮点击它,数据就会对服务器产生不满,从而被插入两次。为了避免这种情况,您需要使用POST/重定向/GET模式将用户重定向到另一个页面或同一个页面。发送303 HTTP响应将告诉浏览器在其历史记录中替换该页面,并避免重新发送已发布的数据。

代码语言:javascript
运行
复制
if (mysqli_query($connection, $register)) {
    header('Location: index.php', true, 303);
    exit;
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35641558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档