我有一张供用户使用的表,一张用于评论,另一张供朋友使用,下面是表结构:评论表:------------------------------------------------| comment_id | user_id_c | commentstatus | ------------------------------------------------| 1 | 1 | Sample comment 1 || 2 | 2 | Sample comment 2 |------------------------------------------------用户表:------------------------------------------------------| id | username | password | Full name |------------------------------------------------------| 1 | user1 (loggedin) | Sample 1 | John || 2 | user2 | Sample 2 | Smith || 3 | user3 | Sample 3 | Andrew || 4 | user4 | Sample 4 | Victor || 3 | user5 | Sample 3 | Robert | -------------------------------------------------------朋友桌---------------------------------------------------| id | friend1 | friend2 | status ---------------------------------------------------| 1 | user1 | user3 | friend| 2 | user1 | user5 | friend| 3 | user2 | user4 | friend---------------------------------------------------目前,如果任何用户发表评论,它会被插入到评论表内的数据库中。现在,如果我登录,我可以从数据库中获取我的所有评论。解释一下,我想通知大家,根据朋友表,用户1是用户3和用户5的朋友。我想要的只是获取登录用户和登录用户的朋友的评论。但是,我无法弄清楚如何获取登录用户及其朋友的评论。我用来获取我的帖子的脚本如下:public function comments(){ global $pdo; $query = $pdo->prepare("SELECT u.*, c.* FROM users u INNER JOIN comments c ON u.id = c.user_id_c WHERE u.id = ".$_SESSION['sid']." ORDER BY c.comment_id DESC"); $query->execute(); return $query->fetchAll(); }然后使用以下代码获取评论:$comments = $get->comments();然后 :foreach($comments as $row){echo $row['Full name']; //user name from user table in the databaseecho $row['commentstatus']; //comment from comments table in the database它正在完美地为登录用户获取数据,无论如何我是否可以同时从数据库中获取登录用户的朋友的评论以及登录用户的评论。
1 回答
烙印99
TA贡献1829条经验 获得超13个赞
你正在寻找这样的东西:
$query = $pdo->prepare("SELECT u.*, c.* FROM users u INNER JOIN comments c ON u.id = c.user_id_c WHERE u.id = ".$_SESSION['sid']." OR c.user_id IN (SELECT friend_id FROM friends WHERE friends.user_id = ".$_SESSION['sid'].") ORDER BY c.comments_id DESC"
- 1 回答
- 0 关注
- 132 浏览
添加回答
举报
0/150
提交
取消