PHP 在数据库中插入重复项 [英] PHP Inserting Duplicates In DB

查看:16
本文介绍了PHP 在数据库中插入重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个注册页面,当前代码运行正常,但我在数据库端收到重复插入.我已经研究并尝试了几种不同的解决方案,但还没有成功.我希望它是我所缺少的非常简单的东西.如何防止我当前的代码插入两次?

I'am attempting to build a register page and the current code runs correctly but I'am getting duplicate inserts on the DB side. I've researched and have tried several different solutions but nothing has worked out yet. I'm hoping its something very simple that I'am missing. How can I prevent my current code from inserting twice?

<?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);
}
?>

推荐答案

如果页面被刷新,或者有人使用返回"按钮再次点击它,数据将被重新发送到服务器并因此被插入两次.您需要使用 POST/REDIRECT/GET 模式将用户重定向到另一个页面或同一页面来避免这种情况.发送 303 HTTP 响应将告诉浏览器在其历史记录中替换该页面并避免重新发送已发布的数据.

If the page is refreshed, or someone hits it again using the "back" button, the data will get resent to the server and thus get inserted twice. You need to redirect the user to another page, or the same page, using the POST/REDIRECT/GET pattern to avoid this. Sending a 303 HTTP response will tell the browser to replace that page in its history and avoid re-sending the posted data.

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

这篇关于PHP 在数据库中插入重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆