HTML表单post方法在页面重新加载时提交重复值

时间:2015-03-22 06:35:00

标签: php html

嘿伙计这是我的第一个PHP项目,所以我是新手,我正在开发一个论坛网站,但我需要在这里开发评论系统,所以我使用以下代码来接受这些值从我的HTML表单,然后将这些值分配给两个PHP变量,并调用我存储在不同PHP文件中的函数。

现在的问题是,每当我刷新网页时,这些值都会自动提交,因此我的数据库充满了我分配给这些变量的相同值,所以我需要你的帮助来解决这个问题。

<html>
<head>
<?php include 'menu.php'?>
<?php include 'include/core.php'?>

<?php 
if($_SERVER['REQUEST_METHOD']=="POST")
{
 $nme = trim($_POST['name']);
 $cmnt = trim($_POST['comments']);

 if(!empty($nme) && !empty($cmnt))
 {

 create_commentsystem($nme,$cmnt);
 unset($nme);
 unset($cmnt);

 }
 else
 {
 echo "Please enter the complete details";
 unset($nme);
 unset($cmnt);
 }

 }
 ?>



<link href="css/main.css" rel="stylesheet" type="text/css">
<link href="css/auth.css" rel="stylesheet" type="text/css">
<title>Doctors Forum</title>

</head>
<body>
<div id="container">
<div class="tab" align="Center">
    Page Content Here
  </div>
  <div class="content">
  <form method="post" name="form1" action="">
  <input class="field" type="text" name="name"   placeholder="Name"           style="width:635px; height:40px;"/></br></br>
  <textarea class="field" name="comments" placeholder="Leave Comments     Here..." style="width:635px; height:100px;"></textarea></br></br>
   <input class="btn"  type="submit" value="Post" style="width:150px;" >
   </form>
   </div>
   <div id="" class="tab" align="center">
    <div>
   </div>
   </body>
   </html>'

这是按下按钮时调用的函数,问题是每次重新加载页面时正在插入相同的记录两次 `function create_commentsystem($ name,$ comments)

    { 

   $name = $_POST['name'];
  $comments = $_POST['comments'];

    $conn = dbConnect();

     mysqli_query($conn, "INSERT INTO comments(name, comments)     VALUES('$name','$comments')");



   $result = mysqli_query($conn, "SELECT * FROM comments ORDER BY id ASC");

    while($row=mysqli_fetch_array($result))
 {
    echo "<div class='comments_content'>";
    echo "<h4><a href='delete_commentsystem()?id=" . $row['id'] . "'> X</a>  </h4>";
    echo "<h1>" . $row['name'] . "</h1>";
    echo "<h2>" . $row['comments'] . "</h2></br></br>";
    echo "<h3>" . $row['date_publish'] . "</h3>";
    echo "</div>";
  }
   $conn->close();


}`

3 个答案:

答案 0 :(得分:1)

当您刷新网页时,浏览器会再次发送请求。最简单的解决方案是在保存注释后使用标头重定向。

示例:

if (add_comment_success()){
    header('Location: http://www.current.url.com/');
    exit();
}

答案 1 :(得分:0)

可以做两件事:

  1. 按照其他答案的建议重新指导
  2. 如果不能选择重定向,请检查数据库以查看是否有相同的名称和注释 存在并且不添加它
  3. 没有其他方法可以阻止这种情况。

答案 2 :(得分:0)

您可以尝试附加

'?submit=true'

到您的操作网址。使用

$_GET['submit']

访问'submit'的值。您的代码可能如下所示

if($_GET['submit'] == true):
  #form processing code
  $_GET['submit'] = false;
  header('your original file');
endif;
相关问题