duanchuli5647 2013-04-26 16:27
浏览 36
已采纳

如何从数据库中选择所有帖子?

In database in table user I have three columns:

id
name
friends

In column friends are names of people who are friends with person whose name is stored in column name. Column friends looks like this:

friendname1,friendname2,friendname3,friendname4

Each of those friends have it's own row where name is equal to their name.

I also have another table called post where I have four columns:

id
name_posted
post
visible

What I would like now, is to select all posts from table post where name_posted is equal to name of the logged in user or any of his friends which are stored in column friends in table user.

Name of the logged in user is stored in variable $user.

For selecting only posts from logged in user I can use this:

$all_posts = mysqli_query($connect_db, "SELECT * FROM post WHERE name_posted='$user' AND visible='yes'");

but I don't know how to include to select also posts from his friends. Something like Facebook have, when you log in and you see your posts plus your friends posts. I don't know how they created that. Sorry for long post, I just wanted to give you detailed description.

  • 写回答

5条回答 默认 最新

  • dowy77780 2013-04-26 16:45
    关注

    Maybe with two querys, first select friends something like this:

    SELECT * FROM user WHERE name='$user' 
    

    You then have all his friends in string like this if I understood correctly :

    friend1,friend2,friend3...
    

    Explode $row['friends'] -> explode(',',$row['friends']); to get all friends names in array and then you can do another select in foreach loop to get all posts from friends and display it the way you like or you can even better do IN in query

    select * from posts where name_posted IN ($row['friends'])
    

    this is the other way, which would be longer

    foreach($friendarray as $k=>$friend){
        ...
          mysqli_query($connect_db,
              "SELECT * from post where name_posted='$friend' AND visible='yes'");
        ...
    }
    

    and also the query you already have to get own posts. Don't forget to escape all values and stuff...

    You could also join two tables but I cant write that query from my mind , would have to sit down and try it with real data but that would be ultimate solution for you.

    Don't know if I hit it right but shout if you need help

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line