复制数据的PHP函数

复制数据的PHP函数,php,mysql,Php,Mysql,我试图用MySQL和PHP制作一个评论部分。但是,由于某种原因,每当我刷新页面时,数据都会重复。每次我刷新页面时都会发生这种情况 范例 它不应该这样做,但它确实这样做了。我认为这与setComment()函数有关,但我不确定 index.php <?php include 'dbh_comments.inc.php'; include 'comments.inc.php'; ?> <!DOCTYPE html> <html> <he

我试图用MySQL和PHP制作一个评论部分。但是,由于某种原因,每当我刷新页面时,数据都会重复。每次我刷新页面时都会发生这种情况

范例

它不应该这样做,但它确实这样做了。我认为这与
setComment()
函数有关,但我不确定

index.php

<?php
    include 'dbh_comments.inc.php';
    include 'comments.inc.php';
?>

<!DOCTYPE html>
<html>
<head>
    <title>Comments</title>
    <link rel="stylesheet" type="text/css" href="comment_styles.css">
</head>
<body>
<?php
    echo"<form method='POST' action='".setComment($conn)."'>
            <input type='hidden' name='uid' value='Anonymous'>
            <textarea name='message'></textarea><br/>
            <button type='submit' name='comment_submit'>Comment</button>
        </form>";
?>
</body>
</html>

评论

您将在文件顶部包含comments.php文件。 在comments.php文件中,您正在调用一个函数(
getComments($conn)
),该函数返回数据


这会被打印在页面的最顶端,其中包含文件。

这是因为web是如何工作的,如果您发布到页面,然后刷新页面,则发布数据。。。嗯,又发了。每次刷新时,你的浏览器可能也会提醒你这一点,对吗

因此,您要做的是在处理POST时将用户重定向回原始表单,因此

if($_POST['message']) {
   ... save message in sql...
   header("Location: /back_to_Somewhere.php");
   exit();
}

在发布后,始终将用户重定向到其他地方是一种很好的做法。

请检查数据库中插入了多少条记录
我希望您的应用程序在插入后取消设置$\u POST数组。
并且您没有单击“刷新”按钮刷新页面。如果是,当警报出现时,您不能按确认。如果是,则插入重复数据


简单地说,我也是这么说的,你的应用程序正在插入重复数据。如果您发布数据而不
unset($\u post)
array,它将在每页加载时插入数据,因为您的插入查询位于
If(isset($\u post['comment\u submit'])和&isset($\u post['message'])!=''
中。插入完成后最好将其取消设置。

是的,你是对的,问题在于:

<?php
    echo"<form method='POST' action='".setComment($conn)."'>
            <input type='hidden' name='uid' value='Anonymous'>
            <textarea name='message'></textarea><br/>
            <button type='submit' name='comment_submit'>Comment</button>
        </form>";
?>

我应该在哪里添加此语句?在哪里调用setComment,甚至在setComment本身内部(开始时),OP在脚本中错误的时刻调用setComment来处理重定向。As重定向必须在任何页面输出之前发生。正如其他人所建议的,这很可能是刷新和重新发布问题。但是,您的action属性应该等于您希望表单数据提交到的url。用户在填写表单并提交表单后,将被带到该url。也许您认为在提交该表单时,会触发函数setComment?当前,每当显示表单时都会调用它。@Progrock,您是对的,表单操作中有一个错误,它必须是url而不是函数。每次访问页面时都可能调用它。但是在插入之前有一个保护。是的,但是页面在发布后不会被重定向,所以如果在任何html之前回显提交的内容之后重新加载页面,则会设置post,这听起来并不理想。但这与提交后页面刷新时将重复行插入数据库有什么关系?
<?php
    echo"<form method='POST' action='".setComment($conn)."'>
            <input type='hidden' name='uid' value='Anonymous'>
            <textarea name='message'></textarea><br/>
            <button type='submit' name='comment_submit'>Comment</button>
        </form>";
?>