用php显示自己和朋友的帖子

时间:2019-03-02 10:20:51

标签: php arrays loops mysqli foreach

我想显示自己的帖子(默认情况下),但如果显示Status = '1'

,还要显示朋友的帖子

我只有这个代码,它显示所有带有相关图像和内容的帖子,因为我不知道如何创建我要寻找的代码。

数据库结构

  

帖子:

| commentid |  comment  | imagesid | author |
---------------------------------------------
|     1     |   fool    |   5557   | test   |
|     2     |  fool2    |   5585   | devel  |
---------------------------------------------
  

多张图片:

| id |  image  | imagesid | author |
------------------------------------
| 1  |  name1  |    5557  | test   |
| 2  |  name2  |    5557  | test   |
| 3  |  name3  |    5585  | devel  |
------------------------------------
  

连接:

| id |  Friend | FriendReferee | Status | 
-----------------------------------------
| 1  |  test   |     devel     |    1   |
-----------------------------------------

当前的获取结构

  

获取图像的实际代码:

 $sql = "SELECT * FROM multiple_image";
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $imgs[$row['imagesid]][$row['id']]= "<img width='' src='../images/".$row['name']."' >"; // array of image id's, with arrays of images inside them.
  } 

 }
  

获取相关文本

$sql = "SELECT * FROM posts";
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $commentsToImages[$row['commentid']] = $row['imagesid'];
      $comments[$row['commentid']] = $row['comment']; 
  }     
 }
  

以分度的div显示结果

foreach($commentsToImages as $commentID =>$imagesID) {
    ?>
<div class='main'>
  <div class='comments'>


<?php echo $comments[$commentID];?>
  </div>
  <div class='pics'>
    <?php
          foreach($imgs[$imagesID] as $img) { 
                  echo $img;
          }
    ?>
  </div>
</div>

<?php
}
?>

我尝试使用JOIN和if else语句来执行此操作,但是并没有按照我的期望进行。

1 个答案:

答案 0 :(得分:1)

在表user_idusersposts上应该有一个connections。此外,friend_id引用了user_id表的users

然后您JOIN posts上的表usersuser_id。通过按ID查找用户名来检索作者。

SELECT
 `p`.`post_id`,
 `p`.`content`    `Post Content`,
 `u`.`user_name`  `Author`
FROM
  `posts`        `p`
INNER JOIN 
  `users`        `u`  USING(`user_id`)
WHERE 
  `p`.`user_id` = 1
;

现在,您可以LEFT JOIN connections表来自您要查看其帖子的朋友的位置。您想过滤所有具有特定posts的{​​{1}}或联接的user_id表具有特定connection的信息,例如friend_id

1

此示例使用的数据库结构为:

SELECT
 `p`.`post_id`,
 `p`.`content`    `Post Content`,
 `u`.`user_name`  `Author`
FROM
  `posts`        `p`
INNER JOIN 
  `users`        `u`  USING(`user_id`)
LEFT JOIN
  `connections`  `c`  ON(`c`.`show_posts`  AND  `p`.`user_id` = `c`.`friend_id`)
WHERE 
  1 in (`p`.`user_id`, `c`.`user_id`)
ORDER BY `p`.`post_id`
;

Try online

相关问题