如何仅显示朋友列表中的帖子。 (正确地)

时间:2015-10-30 15:10:14

标签: php mysql

我的朋友数组只返回一个数字而不是所有数字。

($myfriends = 3)

应该是......

($myfriends = 3 5 7 8 9 12).

如果我在循环中得到它...整个事情都有效,但不是按照我想要的日期顺序显示帖子。 例如:

(post_id 3 oct30 "post goes here")
(post_id 5 oct29 "post goes here")
(post_id 7 oct28 "post goes here")

相反,它显示按日期排序的1个人ID的所有帖子。然后在那个人的所有帖子之后。它最终将显示下一个人及其所有帖子:

(post_id 3 oct30 "post goes here")
(post_id 3 oct29 "post goes here")
(post_id 3 oct28 "post goes here")

(post_id 5 oct30 "post goes here")
(post_id 5 oct29 "post goes here")
(post_id 5 oct28 "post goes here")

依此类推...任何新帖子组都会使用较旧的帖子,而不是转到Feed的顶部。

我希望这是有道理的...抱歉不好的解释和草率的代码

TABLES feed&下面的朋友 两者都有自动增加主'id'作为第一个字段...然后

FEED TABLE
feed (post_id, posted_by, content, date_posted, date_str, pic) VALUES ('$post_id', '$posted_by', '$content', now(), '$date', '$profile_pic')

FRIENDS TABLE
friends (user_id, friend_id) VALUES ('$myId', '$friendId')
<div class="post container">
<?php
$addsql="SELECT * FROM friends WHERE user_id = '$session_id' ORDER by id DESC";
$addquery=mysqli_query($conn, $addsql);

while ($rowa = mysqli_fetch_array($addquery)) {
$myFriends = $rowa['friend_id'];      
?>

<?php
$feedsql = "SELECT * FROM feed WHERE post_id = '$myFriends' ORDER by date_posted DESC";
$result = mysqli_query($conn, $feedsql);

while($row = mysqli_fetch_array($result)) {
$posted_by = $row['posted_by'];
$content = $row['content'];
$time = $row['date_posted'];
$date = $row['date_str'];
$pic = $row['pic'];
$post_id = $row['post_id'];
$upperUser = ucfirst($username);
?>

<?php 
$imgsql = "SELECT * FROM users WHERE username = '$posted_by' ";
$q = mysqli_query($conn, $imgsql);
while($rows = mysqli_fetch_array($q)) {
$image = $rows['image'];
$mem_id = $rows['id'];
if ($posted_by == $upperUser) {
echo " <a href='profile.php?id=$mem_id'><img  src='users/$upperUser/".$image."' alt='MEMBER Pic' /></a>"; 
} else if($posted_by !== $upperUser) {
echo " <a href='profile.php?id=$mem_id'><img  src='users/$posted_by/".$image."' alt='Profile Pic' /></a>"; 
}
} 
?> 

 <div class="each_post">
<h4><a href='profile.php?id=<?php echo $mem_id; ?>'><?php echo ucfirst($posted_by);?></a>  <small class="post_date"><?php echo $date;?></small></h4>
<p class=""><?php echo $content;?></p>
</div>
<?php
}}
?>
</div>

1 个答案:

答案 0 :(得分:0)

问题本身是由在while循环中覆盖$ myFriends变量引起的:

while ($rowa = mysqli_fetch_array($addquery)) {
    $myFriends = $rowa['friend_id'];      
?>

你可以将$ myFriends定义为一个数组并将friend_ids添加到数组中,但是你不应该这样做,因为效率很低。

您可以使用SQL中的JOIN关键字连接多个表。在这种特殊情况下,您将需要一个INNER JOIN(有几种类型的连接,但您需要了解它们。)

$feedsql = "SELECT * FROM feed INNER JOIN friends ON feed.posted_by=friends.friend_id WHERE friends.user_id = '$session_id' ORDER by date_posted DESC";

由于您没有透露您的表结构,我假设feed表中的posting_by字段将决定谁发送了帖子,因此我可以在friend_id字段上加入此字段。如果不是这种情况,那么您需要确定这两个表可以连接到哪些字段。

您甚至可以加入上述2个表格中的用户表格,以获取朋友的详细信息。

相关问题