2013-11-09 88 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并在隐藏字段中回显您的值。 –