大家好,我有两张桌子,第一个桌子叫做“帖子”,看起来像这样id picture title description poster ip posterid .....123 img-2.jpg Title 1 Desc 1 Poster xx 1第二个表叫“爱”,长这个样子id ip userid postid created1 xx 1 123 date 这是我的 MySQL 查询的实际外观:<?php// Get records from the database $query = $db->query("SELECT * FROM posts ORDER BY id DESC LIMIT 10"); if($query->num_rows > 0){ while($row = $query->fetch_assoc()){ $postID = $row['id']; ?> <!-- POST ITEM START --> <div class="post-item"> <div class="post-asset image"> <img src="uploads/<?php echo $row['picture']; ?>"> </div> <div class="post-header"> <h3 class="post-title"><a href="#" data-loader="show"><?php echo $row['title']; ?></a></h3> <span class="post-category"> <a class="favorite-button" href="#" data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>"><span class="favorite-button-icon fa fa-star-o"></span></a> </span> <span class="post-date font17"><i class="fa fa-clock-o"></i> <?php $timeago=get_timeago(strtotime($row['created'])); echo $timeago;?></span> <span class="post-comments font17"><i class="fa fa-comments-o"></i> 1,3k Reaktionen</span> </div> <div class="post-footer"> <a href="#" class="post-author"> <span class="author-img"><img src="img/avatar.png"></span> <span class="author-name">OnePost von<b><?php echo $row['poster']; ?></b></span>我现在想要做的是了解具有其会话 ID(也是用户 ID)的实际用户是否喜欢该帖子,并在是否喜欢该帖子时显示它。
1 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
使用 LEFT JOIN 到love表格并检查帖子是否真的被喜欢/喜欢的IS NOT NULL条件:
<?php
// Get records from the database
$stmt = $db->prepare("
SELECT p.*, (l.postid IS NOT NULL) as is_liked
FROM posts p
LEFT JOIN love l
ON l.postid = p.id
AND l.userid = ?
ORDER BY p.id DESC
LIMIT 10
");
$stmt->bind_param('i', $currentUserId);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$postID = $row['id'];
?>
[...]
您可以访问$row['is_liked']将包含1或的值0。
您需要替换$currentUserId为包含当前使用 ID 的变量。那可能是$_SESSION['userid']。
- 1 回答
- 0 关注
- 109 浏览
添加回答
举报
0/150
提交
取消