MySQL显示基于id的所有记录

时间:2015-03-03 16:01:52

标签: php mysql

所以我试图展示哪些用户喜欢特定的帖子。

代码如下:

$getlikes = mysqli_query($con, "SELECT * FROM likes WHERE post_id = $id");
                        $likes_row = mysqli_fetch_assoc($getlikes);
                        $liked_users = $likes_row['user_id'];

这只会输出一个用户,而有2个用户喜欢这个帖子。

MySQL DB表如下:

id | user_id | post_id

1 | someone | 1

2 | bob | 1

他们都喜欢帖子1,但它只显示someone

我希望他们两个出现,例如:

Someone and Bob liked this post

1 个答案:

答案 0 :(得分:2)

$getlikes = mysqli_query($con, "SELECT * FROM likes WHERE post_id = $id");
while ( $likes_row = mysqli_fetch_assoc($getlikes))
$liked_users[] = $likes_row['user_id'];

如果你喜欢echo那么多,你可以echo这样:

$getlikes = mysqli_query($con, "SELECT * FROM likes WHERE post_id = $id");
while ( $likes_row = mysqli_fetch_assoc($getlikes))
echo $likes_row['user_id'];

我真的很惊讶你有多喜欢回声并且不喜欢数组,所以只为了你, 这是第三种变体,如何使用您的查询,最奇怪的一个:

$liked_users='';
$getlikes = mysqli_query($con, "SELECT * FROM likes WHERE post_id = $id");
while ( $likes_row = mysqli_fetch_assoc($getlikes))
$liked_users.= ($liked_users=='')?$likes_row['user_id']:', '.$likes_row['user_id'];

echo $liked_users;