php mysql" like button"通知

时间:2013-10-03 16:12:41

标签: php mysql

编写与某个帖子相关的所有“喜欢”的php / mysql代码的最短路径是什么,甚至可以显示点击了like按钮的人,如下例所示:

John,Mary,Brian和其他人喜欢这条评论

1 个答案:

答案 0 :(得分:2)

由于您没有提供除您想要的任何其他详细信息,因此这完全基于您可以如何设置数据库的假设。

SQL查询:

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

post_id是你想要分组的东西,所以例如,如果每个评论都有自己的ID,那么你想用它来分组你的喜欢。

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

字段:id,comment_id,post_id,name

所以你会喜欢它:

+--------------+---------------+--------------+--------------+
|    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.