PHP MySQL“喜欢按钮”通知


php mysql "like button" notification

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

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

由于除了您想要的内容之外,您没有提供任何其他详细信息,因此这一切都基于对数据库如何设置的假设。

SQL查询:

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

post_id是您想要分组的内容,因此,例如,如果每个评论都有自己的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.