【问题标题】:My pgsql is adding repeated rows to the table in the database everytime I reload the page每次重新加载页面时,我的 pgsql 都会向数据库中的表添加重复的行
【发布时间】:2021-02-18 18:43:05
【问题描述】:

这是我的 sql:

<?php
$db=pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=preethy1970");
if (isset($_POST['signup'])) {
$query = "INSERT INTO users(user_name,user_password,user_email,user_phone,user_type) VALUES('$_POST[name1]','$_POST[password]','$_POST[email]','$_POST[phoneNumber]','$_POST[usertype]')";
$result=pg_query($query);
 }
?>

这里是html:

<form method="post" action="signUp.php">
  <input id="submit-form" name="name1" placeholder="Name" type="text" required></input>
  <input id="submit-form" name="email" placeholder="Email id" type="email"></input>
  <input id="submit-form" name="phoneNumber" placeholder="Phone Number" type="tel"></input>
  <input id="submit-form" name="password" placeholder="Password" type="password"></input><br>
  <input name="usertype" type="radio" value="0">Student</input>
  <input name="usertype" type="radio" value="1">Faculty</input>
  <input name="usertype" type="radio" value="2">Alumni</input>
  <input id="submit-btn" type="submit" name="signup"  value="Sign Up"></input>
</form>

所以我将转到我的注册页面并添加一些内容,这些内容将添加到用户表中。当我重新加载页面时,即使字段为空且未单击提交按钮,先前的内容也会再次添加为新行。为什么会这样?

【问题讨论】:

    标签: php database postgresql


    【解决方案1】:

    @richyen 是正确的。

    “当通过 HTTP POST 请求将 Web 表单提交到服务器时,尝试刷新服务器响应可能会导致重新提交原始 POST 的内容,从而可能导致不希望的结果,例如重复的 Web 购买。”

    这个问题是众所周知的,可以通过使用 Post-Redirect-Get 模式来解决。

    Post-Redirect-Get

    这是关于它的另一个答案。 https://stackoverflow.com/a/10827315/909973

    这是一个简单的 Post-Redirect-Get 实现示例。 https://stackoverflow.com/a/4142969/909973

    【讨论】:

      【解决方案2】:

      发生这种情况是因为您没有区分表单发布和页面加载。每次加载页面时,您都在调用 php 代码。如果只想在提交表单时插入,则需要检查$_POST["signup"],并仅在if (isset($_POST['signup'])) 返回true 或具有"submit" 值时运行SQL 代码

      【讨论】:

      • 所以我添加了一个 if 条件,它是不是在错误的地方?是否应该将整个事物(来自 $db)包含在 if 条件中?
      • 你试过了吗?我认为您可能需要确认它是否按您的预期工作
      • 是的,我试过了,没有按预期工作。现在,我想我会坚持重定向
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 2018-01-23
      • 2018-10-06
      • 2014-06-20
      相关资源
      最近更新 更多