-5

编写一个 php/mysql 代码的最短方法是什么,该代码将与某个帖子相关的所有“喜欢”分组,甚至显示点击了喜欢按钮的人,如下例所示:

约翰、玛丽、布赖恩和其他人喜欢这个评论

4

1 回答 1

2

由于您没有提供除您想要的以外的任何其他详细信息,因此这一切都基于您的数据库可能设置方式的假设。

SQL查询:

 SELECT * FROM likes WHERE (comment or post id) = 'ID'

post_id 是您想要分组的东西,例如,如果每个评论都有自己的 ID,那么您希望以此来对您的喜欢进行分组。

我喜欢的数据库是这样设置的:

字段:id、comment_id、post_id、名称

所以你会像这样:

+--------------+---------------+--------------+--------------+
|    ID        |   comment_id  |    post_id   |   name       |
+--------------+---------------+--------------+--------------+
|     1        |     382       |     null     |   John       |
|     2        |     382       |     null     |   Mary       |
|     3        |     null      |     189      |   Brian      |
|     4        |     null      |     189      |   Joe        |
|     5        |     382       |     null     |   Ryan       |
|     6        |     382       |     null     |   Bell       |
+--------------+---------------+--------------+--------------+

因此,如果您使用 SQL 脚本:

SElECT * FROM likes WHERE comment_id = '382'

您将获得以下信息:

+--------------+---------------+--------------+--------------+
|    ID        |   comment_id  |    post_id   |   name       |
+--------------+---------------+--------------+--------------+
|     1        |     382       |     null     |   John       |
|     2        |     382       |     null     |   Mary       |
|     5        |     382       |     null     |   Ryan       |
|     6        |     382       |     null     |   Bell       |
+--------------+---------------+--------------+--------------+

然后你会像这样运行一个脚本(假设它是 PHP):

$num = 0; // This is used as an identifier
$numrows = mysqli_num_rows($getdata); // Count the number of likes on your comment or post

if($numrows > 3) { 
    $ending = 'and others like this comment.'; // If there are more than 3 likes, it ends this way
} else { 
    $ending = 'like this comment.'; // If there are less than or equal to 3 likes, it will end this way
}

while($data = mysqli_fetch_array($getdata)) {
    if($num => 3) { // This says that if the $num is less than or equal to 3, do the following
        // This will be used to list the first 3 names from your database and put them in a string like: name1, name2, name3, 
        $names = $data['name'].', ';
        // This adds a number to the $num variable.
        $num++;
    }
}

echo $names.' '.$ending; //Finally, echo the result, in this case, it will be: John, Mary, Ryan, and other like this comment.
于 2013-10-03T16:38:59.480 回答