Search code examples
phphtmlmysqlsqlposts

Display following users posts


So I have a project that I'm working on where you can "follow" another user, and view their posts, along with other users. Like Facebook. Something like this

Bob: I love SO
Alex: I love SO too
Ally: Me three! 

So this is what I'm doing so far. I'm selecting the people the signed in user is following, all of which are stored in a table called followers. Here's what it looks like

+-----+-------------+-----------+
| id  | follow_from | follow_to |
+-----+-------------+-----------+
| 319 | bob         | alex      |
| 320 | ally        | alex      |
| 320 | alex        | ally      |
+-----+-------------+-----------+

As you can see it displays the user and who they're following. So this is how I retrieve a list of who you're following

SELECT * FROM followers WHERE follow_from = :username  

Now that will return

Bob
Alex
Ally 

Now onto the posts. I store the posts in another table called "posts". This is what that looks like

+----+-----------+---------+-----------+--------------+------------+
| id | post_user | post_ip | post_date | post_content | post_likes |
+----+-----------+---------+-----------+--------------+------------+
|  1 | alex      | ::1     |           | I like cats  | 0          |
+----+-----------+---------+-----------+--------------+------------+

So I'd assume that both Bob and Ally see alex's post. The issue I'm having is retrieving the posts and basically merging them together. Since my posts are in another table I couldn't find a way to figure out which post is which.

I've tried this

SELECT * FROM posts WHERE followed_user=:username ORDER BY post_date DESC 

But couldn't figure out a way to use :username with multiple username. Like the followers. So basically my question is, how can I display multiple posts, from multiple users, on one wall. Or if anyone can solve how I can select posts from multiple people you're following.

Just to add on when I do SELECT * FROM followers WHERE follow_from = :username and run

$posts = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $posts[] =  array(
    'follow_to' => $row['follow_to']
);
}    

And do

foreach($posts as $post) {
            echo $post['follow_to'];
}

I get a list of the followers, so I'd assume this will have something to do with retrieval of the posts.


Solution

  • You are looking for JOIN/Subquery,

    SELECT
        *
    FROM
        posts
    WHERE
        post_user IN 
        (
            SELECT follow_to FROM followers WHERE follow_from = :user
        )
    

    Update

    If you'd like to load a list of posts by a single person as well as the followers,

    SELECT
        *
    FROM
        posts
    WHERE
        post_user IN 
        (
            SELECT 
                follow_from 
            FROM 
                followers 
            WHERE 
                follow_to = :user 
                OR
                follow_from = :user 
        )