PHP将用户评论添加到图库

时间:2013-03-01 10:32:36

标签: php loops comments gallery

我真的很难为用户生成的php库添加评论。 我有一个图像数据库表:userimage(id,imagepath,userid,description)和table image_comment与外键列(comment_id,comment,auther,image_id,comment_date)。 我的方法是使用sql查询创建一个函数,并在我的gallery的while循环中调用它 - 希望在循环中为匹配的图像提取正确的注释。
FUNCTION:

function getImageComments($imageId){
$query = "SELECT userimage.id, image_id, comment, id, comment_date
FROM userimage, image_comment
WHERE image_comment.image_id=userimage.id
ORDER BY comment_id DESC";
mysql_query($query);}

循环中的变量和功能调用:

while($gallery_data=mysql_fetch_assoc($gallery_result))
{
$gallery_out .= "<div class=\"pic-container\"><img src=\"".$gallery_data['path']."\">";

$imageId = $gallery_data['id'];
$gallery_out .= getImageComments($imageId);

这对我来说绝对没有任何意义,我只是放在这里,没有幻想看怎么继续......

2 个答案:

答案 0 :(得分:1)

function getImageComments($imageId){
   $query = "SELECT userimage.id, image_id, comment, id, comment_date
   FROM userimage, image_comment
   WHERE image_comment.image_id=userimage.id
   AND userimage.id='$imageId';
   ORDER BY comment_id DESC";
   $result=mysql_query($query);
   //do something with this query result, since you are doing $gallery_out .= getImageComments($imageId);
   $return_value="";
   while($row=mysql_fetch_array($result)){
       $return_value.="<div>$row[2]</div>";
   }  
   return $return_value;
}

另外,如果您正在开发新代码,请考虑使用mysqli_ functions或PDO!

答案 1 :(得分:0)

即使代码与你的代码完全不同。我做了类似于你的画廊的事情,每个帖子只使用了总共​​两个查询而不是1 + 1。

部分$ user-&gt; GetPosts(); (我遗漏了查询)

$posts = []; 
$post_IDs = [];
while($row = $result->fetch_assoc())
{
    if(!in_array($row['object_ID'], $post_IDs))
        $post_IDs[] = $row['object_ID'];

    $posts[] = new Post($row, $_SESSION['uid']);
}

if(count($post_IDs) == 0)
    return $posts;

$result = $this->getComments($post_IDs);

while($row = $result->fetch_assoc())
{
    $comment = new Comment($row, $_SESSION['uid']);
    foreach($posts as $post)
        if($post->object_ID == $comment->object_commented_ID)
            $post->comments[] = $comment;
}

return $posts;

查询$ this-&gt; getComments($ post_IDs);这是查询:

$object_IDs = implode(",", $object_IDs);

$query = 
    "SELECT 
        comments.object_ID, comments.object_commented_ID, comments.entity_ID, 
        comments.datetime, comments.text, 
        objects.likes, SUM(IF(likes.user_ID=?, 1, 0)) AS allowLike, 
    users.first_name, users.last_name, userinfo.image_ID FROM comments 
    LEFT JOIN users ON users.entity_ID=comments.entity_ID 
    LEFT JOIN userinfo ON users.entity_ID=userinfo.user_ID 
    LEFT JOIN likes ON likes.object_ID=comments.object_ID 
    LEFT JOIN objects ON objects.ID=comments.object_ID
    WHERE comments.object_commented_ID IN(". $object_IDs .") 
    GROUP BY comments.object_ID ORDER BY comments.datetime ASC LIMIT 0,100";

然后在一个单独的foreach循环中,我打电话给

$post->Show(); //Which in turn calls foreach $comment->Show();