查询返回未被跟踪的用户结果

时间:2014-07-13 03:30:28

标签: php mysql sql database

首先,这将是相当漫长和复杂的。所以,如果你仔细阅读,谢谢。

所以我在PHP中有一个跟随和发布系统。所以我可以关注Alex,我会看到Alex的帖子,以及我在主墙上的帖子。如果我不跟随他,我就不会看到他的帖子了。这就是查询的样子

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

从您关注的人那里获取帖子。井应该做的事情。这里的帖子是什么样的

+----+-----------+---------+------------------------+--------------+------------+
| id | post_user | post_ip | post_date              | post_content | post_likes |
+----+-----------+---------+------------------------+--------------+------------+
| 40 | idris     | ::1     | 07/09/2014 11:19:47 pm | I like food  | 0          | 
+----+-----------+---------+------------------------+--------------+------------+

现在说Scott这是另一个用户,登录。他走到他的墙上,他可以看到我的帖子,即使他没有关注我。这就是我遇到的问题。这是followers

+-----+-------------+-----------+
| id  | follow_from | follow_to |
+-----+-------------+-----------+
| 358 | idris       | scott     |
+-----+-------------+-----------+
当我看着自己的墙时,我也希望看到他的帖子。但我什么也看不见(当数据库中有帖子时)。基本上我的问题是,为什么Scott在他的墙上看到我的帖子,即使他没有关注我。

我有很多代码,但我会尝试发布重要的部分

我如何运行查询

$qry = $con->prepare("SELECT * 
                      FROM posts 
                      WHERE post_user IN ( SELECT follow_from 
                                           FROM followers 
                                           WHERE follow_to = :user 
                                            OR follow_from = :user )");
$qry->bindValue(':user', $username, PDO::PARAM_STR);
$qry->execute();

我如何检查用户是否关注

if($_SESSION['loggedIn'] == true){
    $result1 = $con->prepare("SELECT * 
                              FROM followers 
                              WHERE follow_from = :user 
                              AND follow_to = :post_id");
    $result1->bindParam(':user', $username);
    $result1->bindParam(':post_id', $username);
    $result1->execute();
    $reprint = $result1->fetch(PDO::FETCH_ASSOC);
}

if($reprint > 1){
    $usr_flw = true;
}
else{
    $usr_flw = false;
}

最后我如何回复帖子

    $posts = array();
    while($row = $qry->fetch(PDO::FETCH_ASSOC)){
        $posts[] =  array(
        'post_user' => $row['post_user'],
        'id' => $row['id'],
        'post_date' => $row['post_date'],
        'post_likes' => $row['post_likes'],
        'post_content' => $row['post_content']
    );
    }   

2 个答案:

答案 0 :(得分:2)

请改为尝试:

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

答案 1 :(得分:0)

假设follow_from是关注者,follow_to是关注用户,则子查询应如下所示:

( SELECT follow_to FROM followers WHERE follow_from = :user )

这将返回被提供用户跟随的用户。