刷新站点时,我的php页面中的帖子重复

9w11ddsr  于 2023-02-07  发布在  PHP
关注(0)|答案(1)|浏览(116)

对不起,我刚开始编程时很不擅长。
我无法使我的帖子系统工作,因为如果我刷新页面,评论区的帖子会重复
我只使用HTML和PHP我不知道其他任何东西也是一个论坛,我和我的朋友我的代码是:
上面也有代码,但这并不重要

<form action="" method="POST">

    <label> Topic: 
    <input type="text" name="Topic" class="Input" style="width: 300px" required>
   </label>
   <br><br>
   <label> Name: 
    <input type="text" name="Name" class="Input" style="width: 225px" required>
   </label>
   <br><br>
   <label> Comment: <br>
    <textarea name="Comment" class="Input" style="width: 300px" required></textarea>
   </label>
   <br><br>
   <input type="Submit" name="Submit" value="Submit" class="Submit">

<!--idk-->

</form>
</center>
<hr>
    <br>



</body>

<!--posts-->

 </html>
<html>
 <center>
 </html>
<?php
 
 if($_POST['Submit']){
  print "<h1>Your comment has been submitted!</h1>";
 }
  ?>

<html>
</center>
</html>

<?php
  $Topic = $_POST['Topic'];
  $Name = $_POST['Name'];
  $Comment = $_POST['Comment'];

  
  #Get old comments
  $old = fopen("comments.txt", "r+t");
  $old_comments = fread($old, 1024);

  #Delete everything, write down new and old comments
  $write = fopen("comments.txt", "w+");
  $string = "<b>".$Topic."</b><br>".$Name."</b><br>".$Comment."</br>\n".$old_comments;
  fwrite($write, $string);
  fclose($write);
  fclose($old);
 

 #Read comments
 $read = fopen("comments.txt", "r+t");
 echo "<br><br>Comments<hr>".fread($read, 1024);
 fclose($read);

 ?>

帮帮忙
我不想重复

oug3syen

oug3syen1#

您所面临的问题是由于您将评论附加到“comments.txt”文本文件的方式。问题是每次发送评论时,所有旧的和新的评论都被写入一个文本文件。因此,当您刷新页面时,相同的评论会重复出现。
希望下面的代码能有所帮助

<?php
  $Topic = $_POST['Topic'];
  $Name = $_POST['Name'];
  $Comment = $_POST['Comment'];

  # Write the new comment to the top of the file
  $write = fopen("comments.txt", "a+");
  $string = "<b>".$Topic."</b><br>".$Name."</b><br>".$Comment."</br>\n";
  fwrite($write, $string);
  fclose($write);
 

  # Read comments from the file
  $read = fopen("comments.txt", "r");
  echo "<br><br>Comments<hr>";
  while(!feof($read)){
    $line = fgets($read);
    echo $line."<br>";
  }
  fclose($read);
?>

相关问题