1

我真的很努力向我制作的用户生成的 php 库添加评论。我有一个用于图像的数据库表:userimage(id、imagepath、userid、description)和带有外键列(comment_id、comment、auther、image_id、comment_date)的表 image_comment。我的方法是使用 sql 查询创建一个函数,并在我的画廊的 while 循环中调用它——希望在循环中提取正确的注释到匹配的图像。
功能:

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 循环中的变量和函数调用:

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);

这对我来说绝对没有任何作用,我只是在这里放养,没有幻想看看如何继续......

4

2 回答 2

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_ 函数或 PDO!

于 2013-03-01T10:41:03.123 回答
0

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

$user->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->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();
于 2013-03-01T10:56:39.283 回答