2013-11-09 72 views
0

海我試圖做一個評論系統使用PHP和MySQL(沒有jQuery或AJAX) 問題是如何找到帖子的用戶名的ID我用了一個while循環爲它發佈到所有帖子到目前爲止,我在這裏.....如何查詢獲取特定的帖子ID?

//user data is set 
if (isset($_POST['comment'])) { 
    //variables to post in database 
    $comment = $_POST['comment']; 
    $com_from = $_SESSION['user']; 
    $com_to = $_GET['u']; 
    $com_time = date("Y-m-d H:i:s"); 
    $u = $_GET['u']; 

    //query to get the id of the post in the `post` table 
    $que = mysql_query("SELECT * FROM posts WHERE `post_to` = '$u'"); 
    if ($que) { 
     //loop through all the posts ad get all ID 
     while ($ro = mysql_fetch_array($que)) { 
      $pst_id = $ro['post_id']; 
      //query inside the while loop for getting the post ID i think here is the problem 
      if (!empty($_POST['comment'])) { 
       $com_query = mysql_query("INSERT INTO comments SELECT '','$comment',`post_id`,'$com_from','$com_to','$com_time' FROM `posts` WHERE `posts`.`post_id` = $pst_id"); 
      } 
     } 
    } 
} 
+0

什麼是'$ u'和'$ com_to'? –

+2

您提供的代碼和評論不可讀。 –

+0

@HamedKamrava $ u是$ _GET ['u'],其中url是profile.php?u =用戶名和$ com_to對用戶發表評論(意味着用戶的帖子所在的位置) –

回答

0

我提供插入查詢與我有限的瞭解,

$pst_id = $_POST['postid']; // from form 

$com_query = mysql_query("INSERT INTO comments values ('$comment','$pst_id','$com_from','$com_to','$com_time') "); 

我可以幫你多,如果您共享comments表結構。

注意使用mysqli_ *函數,而不是mysql_ *函數(deprecated)

+0

謝謝:D並等待我發佈我的評論表結構和'post_id'是一個外鍵 –

+0

ID |評論| post_id | comment_by |評論_ | | comment_time | 'post_id'是外鍵 –

+0

雖然提交您需要傳遞的評論或'$ _POST'帖子表'主'ID。然後在這裏檢索帖子ID並相應地更新評論。 –

1

首先你不要都去通過迴路quering職位表。 如果你正在評論一個特定的帖子,以隱藏類型的HTML格式傳遞它的ID。

// here 1 is id of post 
<input type="hidden" name="postid" value="1"> 

然後,你可以寫插入查詢,如:

if (isset($_POST['comment'])) { 
    //variables to post in database 
    $comment = $_POST['comment']; 
    $com_from = $_SESSION['user']; 
    // $com_to is post id and i believe comment table contain field to store post id 
    $com_to = $_POST['postid']; 
    $com_time = date("Y-m-d H:i:s"); 
$que = mysql_query("INSERT INTO comments VALUES('$comment','$com_to','$com_from','$com_time')"); 
} 
+0

如何動態使用它的很多帖子? –

+0

你知道像有很多帖子如何插入不同的值的HTML? –

+0

動態獲取post_id並在隱藏字段中回顯您的值。 –