2015-09-07 97 views
0

我正在構建一個非常基礎的論壇,可以對帖子發表評論。正如您所看到的,此代碼顯示了評論以及評論作者何時與登錄用戶相同時,它應該顯示刪除按鈕以刪除評論。現在的問題是,當我點擊刪除按鈕時,它會刪除帖子上的所有評論,而不僅僅是評論旁邊的刪除按鈕。MYSQL刪除特定行按鈕PHP

我的「意見」表有列ID,盤標識符,comment_username,評論和COMMENT_TIME,其中從「意見」盤標識符列指的是ID列在表「dicussions」

<?php 

    $id = mysql_real_escape_string($_GET['id']); 
    $query = 'SELECT * FROM discussions WHERE `id` = '.$id.' LIMIT 1'; 
    $result = mysql_query($query); 
    $row = mysql_fetch_array($result); 

    ?> 
      <h2><? echo $row['category'] . $row['topic']; ?></h2> 
      <div>Posted on <? echo $row['date_time']; ?> by <? echo $row['username'] ?></div> 
      <div><? echo $row['discussion']; ?></div> 

    <? 

$result_comments = mysql_query("SELECT * FROM comments WHERE discid = $id ORDER BY comment_time ASC"); 

     while ($record = mysql_fetch_array($result_comments)) 

     { 

     ?> 
       <form action="" method="POST" > 
        <? echo $record['comment_username']. $record['comment_time'] ?> 

        <!-- if comment from logged in user, show delete option --> 
        <? 
        if ($record['comment_username'] == $log_username) 
        { 
         echo '<span><button title="Delete comment" value="' . $record['id'] .'" name="deletecommentbutton" type="submit">X</button></span>'; 
        } 
        if(isset($_POST['deletecommentbutton'])) 
        { 
         $commentid = $record['id']; 
         $result_delete = mysql_query("DELETE from comments WHERE id='$commentid'"); 
         header("Location: url/discussion_view.php?id=".$_GET['id'].""); 
        } 
        ?> 

       <div><? echo $record['comment'] ?></div></form> 

      <?php } ?> 

回答

4

第一所有你不應該使用mysql_*函數了。它已被棄用。

相反,您可以使用PDO

而對於你的問題,陳述if(isset($_POST['deletecommentbutton']))true針對給定的每一條評論,因爲你沒有檢查所選評論的ID。 您應該將刪除代碼移到循環外,並僅對選定的ID執行。

+0

如何僅爲選定的ID執行? –

+0

只需使用'$ _POST ['deletecommentbutton']'這是所選評論的ID。但不要忘記消毒! –

+0

你可以給我一個例子或一種方式來開始?我無法工作:( –