2015-12-16 114 views
0

我正在對我的網站上的帖子系統發表評論,結果是最新的評論被新的評論取代。我希望所有的評論留下來,而不僅僅是一個。這個PHP評論系統不工作?

<?php 
$placement=290; 
$comment=fgets($file); 
while ($comment!="") { 

    $placement=$placement+5; 
    echo'<div style="left:10px; position:relative; top:'.$placement.'px; border:solid; right:10px; height:75px;">'; 
    $comment=fgets($file); 
    echo "<p>".$comment."</p>"; 
    echo'</div>'; 
} 

$placement2=$placement+5; 

if (isset($_SESSION['Username'])) { 
    echo'<form method="POST" action="">'; 
    echo'<input type="text" columns="10" maxlength="500" style="position:relative; left:50px; width:80%; height:50px; resize:none; top:'.$placement2.'px;" name="comment" placeholder="Leave a comment! (max 500 characters)" >'; 
} 

if (isset($_POST['comment']) or isset($_POST['submit'])) { 

    if (!empty($_POST['comment'])) { 

     $file=fopen('Questions/question'.$_GET['qid'],"r"); 
     $name=fgets($file); 
     $info=fgets($file); 
     $user=fgets($file); 
     $n=fgets($file); 
     $number=1; 

     while($number<$n) { 
      $comment=fgets($file); 
      define("comment".$number,$comment); 
      echo $number; 
      $number=$number+1; 
     } 

     define("comment".$number,$_POST['comment']); 
     echo trim(constant("comment1")); 

     $file=fopen('Questions/question'.$_GET['qid'],"w"); 
     fwrite($file,$name); 
     fwrite($file,$info); 
     fwrite($file,$user); 
     fwrite($file,$n); 
     $number2=1; 
     while($number2<$number) { 
      $number2=$number2+1; 
      fwrite($file, constant("comment".$number2)."\n"); 
      echo constant("comment".$number2)."\n"; 
     } 
    } 
} 
?> 

我知道什麼是錯的,我只是不知道是什麼。另外,沒有錯誤。

+0

如果您爲此使用了數據庫,那麼您可以更輕鬆一點。 – jeroen

+0

隨着我使用的免費主機,我無法使用SQL。 –

+1

一些合理的代碼縮進會使閱讀更重要,而且更重要的是調試這些代碼更容易 – RiggsFolly

回答

1

您正在以w模式打開文件,該模式將指針放在文件的開頭,並覆蓋內容。

有關更多信息,請參閱PHP fopen() docs

你最有可能想aa+模式,就像這樣:

​​

注:直接寫入基於一個$ _GET變量文件是不好的做法。您需要清理該變量。 (您應該清理所有用戶輸入)。在這種情況下,消毒的最簡單的形式是這樣的:

// typecast to an integer 
$question_id = (int)$_GET['qid']; 
// then use the known integer value 
$file = fopen('Questions/question' . $question_id,"a+"); 

最後,對你的問題的commments是正確的:你將有一個更強大的系統,並且更輕鬆地編碼,如果你使用數據庫。 PHP和mysql很好,但一定要使用mysqliPDO庫 - 不要使用mysql_庫:http://php.net/manual/en/mysqlinfo.api.choosing.php

+0

也許我沒有通過文件打開類型進行足夠的搜索。謝謝。 –