我有以下三个表 - users_thoughts
,users
和post_favourites
。我的社交网站中有一个功能,允许用户收藏帖子(帖子存储在user_thoughts
中,当帖子有利时,即调用favourite_post.php
时,它会将收藏夹存储在{{ 1}}表)。
如果登录的用户不赞成帖子,则会显示post_favourites
。但是,如果用户 HAS 偏好某个帖子,则会显示Glyphicon heart-empty
。
假设我的表中有以下行:
Glyphicon-heart
表:
users
id: 1
first_name: conor
id: 2
first_name: Alice
id: 3
first_name: Anderson
表:
user_thoughts
id: 100
message: This is a post by Alice.
added_by: Alice
id: 101
message: This is a post by Anderson
added_by: Anderson
表:
post_favourites
假设我以id: 1
user_id: 1 (This is the id of the user who has favourited the post, see users table)
thought_id: 101
身份登录。正如您所看到的,Conor
赞成Conor
的帖子,因此应显示Anderson
,因为已登录的用户已经赞成安德森的帖子。但是Glyphicon-heart
正在出现,尽管我的数据库表明conor赞成安德森的职位。
以下是我的疑问:
注意:Glyphicon-heart-empty
是为登录用户创建的会话变量。
$username
我需要它,所以已登录的用户的优惠帖子会显示$count = mysqli_query ($connect, "SELECT * FROM user_thoughts");
while ($row = mysqli_fetch_assoc($get_thoughts_from_db)) {
$thought_id = $row['id'];
}
// Get all user_ids attachted to a thought ($thought_id)
$get_user_id = mysqli_query ($connect, "SELECT * FROM post_favourites WHERE thought_id = '$thought_id'");
$id_fetch = mysqli_fetch_assoc ($get_user_id);
$all_user_id = $id_fetch ['user_id'];
$post_id = $id_fetch ['thought_id'];
// get id of users from users table
$get__id = mysqli_query ($connect, "SELECT id FROM users WHERE username = '$username'");
$id_fetch2 = mysqli_fetch_assoc ($get__id);
$logged_in_user = $id_fetch2 ['id'];
if ($post_id == $thought_id){
// If the post has already been favourited by the username, then display this icon with funtionality.
if ($all_user_id == $logged_in_user){
echo "$get_num_of_favs
<a href='/inc/unfavourite_post.php?id=";?><?php echo $thought_id;?><?php echo "'>
<span class='glyphicon glyphicon-heart' aria-hidden='true' style='padding-right: 5px;'></span>
</a>";
}
// if the post hasn't been favourited by the username, display this icon.
else {
echo "$get_num_of_favs
<a href='/inc/favourite_post.php?id=";?><?php echo $thought_id;?><?php echo "'>
<span class='glyphicon glyphicon-heart-empty' aria-hidden='true' style='padding-right: 5px;'></span>
</a>";
}
}
图标,即执行if语句。但目前,安德森的帖子heart
- 受到康纳的青睐,正在展示This is a post by Anderson
- 意味着其他声明正在执行,我不知道为什么?
答案 0 :(得分:0)
如果没有你的数据,我无法确定,但是我会把钱归结为不止一个用户对这篇文章的收藏。然后,第一个结果由
返回$get_user_id = mysqli_query ($connect, "SELECT * FROM post_favourites WHERE thought_id = '$thought_id'");
将没有当前登录用户的user_id。您应该将$ logged_in_user添加到WHERE子句:
$get_user_id = mysqli_query ($connect, "SELECT * FROM post_favourites WHERE thought_id = '$thought_id' AND user_id = '$logged_in_user'");
(在查询之前不要忘记转义任何数据!)
答案 1 :(得分:0)
可以使用SQL查询中的joins替换php中的整个复杂逻辑,以组合来自所有相关表的数据:
select *
from user_thoughts u
left join post_favourites p on u.id=p.thought_id and u.user_id=$_SESSION['userid']
$_SESSION['userid']
是当前登录用户的用户ID。将其与用户名一起存储在会话中。
当你在php中循环结果集时,如果think_id ==''(空字符串),那么你知道当前用户还不喜欢这篇文章。