php页面中的重复注释
我有php页面中的注释代码 但当我在发布评论后刷新页面时,同样的评论也会被发布 并存储在数据库中。 请帮帮我php页面中的重复注释,php,mysql,Php,Mysql,我有php页面中的注释代码 但当我在发布评论后刷新页面时,同样的评论也会被发布 并存储在数据库中。 请帮帮我 <?php mysql_connect("localhost","root","password"); mysql_select_db("comments"); $name=$_POST['name']; $comment=$_POST['comment']; $submit=$_POST['submit']; $dbLink = mysql_connect("localhos
<?php
mysql_connect("localhost","root","password");
mysql_select_db("comments");
$name=$_POST['name'];
$comment=$_POST['comment'];
$submit=$_POST['submit'];
$dbLink = mysql_connect("localhost", "root", "a12345");
mysql_query("SET character_set_client=utf8", $dbLink);
mysql_query("SET character_set_connection=utf8", $dbLink);
if($submit)
{
if($name&&$comment)
{
$insert=mysql_query("INSERT INTO comment (name,comment) VALUES ('$name','$comment') ");
}
else
{
echo "please fill out all fields";
}}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Comment box</title>
</head>
<body>
<center>
<form action="index.php" method="POST">
<table>
<tr><td>Name: <br><input type="text" name="name"/></td></tr>
<tr><td colspan="2">Comment: </td></tr>
<tr><td colspan="5"><textarea name="comment" rows="10" cols="50"></textarea></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Comment"></td></tr>
</table>
</form>
<?php
$dbLink = mysql_connect("localhost", "root", "a12345");
mysql_query("SET character_set_results=utf8", $dbLink);
mb_language('uni');
mb_internal_encoding('UTF-8');
$getquery=mysql_query("SELECT * FROM comment ORDER BY id DESC");
while($rows=mysql_fetch_assoc($getquery))
{
$id=$rows['id'];
$name=$rows['name'];
$comment=$rows['comment'];
echo $name . '<br/>' . '<br/>' . $comment . '<br/>' . '<br/>' . '<hr size="1"/>'
;
}
?>
</body>
</html>
但是没有好处。使用post完成工作后,您可以使用
unset($\u post)
取消设置post
。
这将清空post,刷新将不会再次带来值。您可以在$insert
查询之后添加unset()
$insert=mysql_query("INSERT INTO comment (name,comment) VALUES ('$name','$comment') ");
unset($_POST['submit']);
header("location:yourfile.php");
提交评论后,如果刷新页面,则在上提交相同的评论。这就是它们被复制的原因 处理此问题的最佳方法是将插入查询放入另一个php文件中,然后在提交后重定向到评论页面;或者如果希望将其保留在同一文件中,则在将评论插入数据库后,使用
header
函数重定向到同一页面
一种简单的修复方法:
if($submit)
{
if($name && $comment)
{
$insert=mysql_query("INSERT INTO comment (name,comment) VALUES ('$name','$comment') ");
header( 'Location: http://the url of your page') ;
}
else
{
echo "please fill out all fields";
}
}
请注意,您的代码不安全 避免这种情况
$submit = isset($_POST['submit']) ?
$_POST['submit'] : '';
和使用
if(isset($_POST['submit']))
{
//here the insertion query..
}
不去上班。刷新页面后,它会将“$\u POST”的值设置为提交的内容,并插入到数据库中。这不是解决方案。这是另一种选择。如果需要在同一页上保存,为什么要创建单独的文件。这是一个解决方案。我建议要么使用单独的php文件,要么在不传递POST信息的情况下刷新到同一页面。当你给出否定点时,确保你理解问题和答案。
if(isset($_POST['submit']))
{
//here the insertion query..
}