如何根据另一个表参数

时间:2016-08-16 19:19:25

标签: php mysql

我已经使用PHP和Mysql构建了一个类似于以下系统的Twitter,我想列出用户按照用户跟随的关注者。有两个与此操作相关的关系表:USERS和FOLLOW。

user_id正在关注的那个。

follow_id正在关注的人。

created发生以下事件的日期。

--------------------------------------------------
|user_id |follow_id |  created  |
--------------------------------------------------
| 23      | 5       |2016-08-09 |
--------------------------------------------------

USERS

--------------------------------------------------
|user_id |  name  |
-------------------------------------------------
| 5      |John Doe|
--------------------------------------------------

这个php Mysql函数可以获得某个用户的关注者。

<?php 
public static function find_followers($user_id){
    global $database;

    $followers_ids = array();
    $sql = "SELECT user_id 
            FROM follow 
            WHERE followed_id = '{$user_id}' 
            ORDER BY created";
    $result = $database->query($sql);
    while($follower = $database->fetch_array($result)){
        array_push($followers_ids, $follower['user_id']);
    }
    if(count($followers_ids)){
        $id_strings = join(',', $followers_ids);

        $sql = "SELECT * FROM users WHERE id IN ($id_strings)";
        $followers = self::find_by_sql($sql);
        return $followers;
    }
} 

?>

驱散粉丝的代码

<?php 
$followers = find_followers($id);

foreach($followers as $follower){

echo $follower->full_name() . "followed you.<br/>"; 
?>

目前,关注者列表是按照创建用户的创建顺序排列的,我希望根据用户跟随用户的顺序显示它们。怎么办呢?

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以在两个表上使用连接,而不是对数据库进行多次调用。 SQL将是:

SELECT user.user_id, user.name /*The user that is followings details*/
FROM users
JOIN follow ON user.user_id = follow.follow_id /*You want the info for follower*/
WHERE follow.user_id = '{$user_id}' /*Only where the user is this user*/
ORDER BY follow.created /*Based on question this is the date a follow happened*/

现在PHP可以成为(假设$ database是mysqli但不确定):

<?php 
    public static function find_followers($user_id){
        global $database;

        $followers_ids = array();
        $sql = "SELECT user.user_id, user.name
            FROM users
            JOIN follow ON user.user_id = follow.follow_id
            WHERE follow.user_id = '{$user_id}' 
            ORDER BY follow.created";

        //If $user_id is user input you should do a prepared statement.
        $result = $database->query($sql);
        $followers = $database->mysqli_fetch_all($result);

        return $followers;
    }
} 

?>

您的观点可以保持不变:

<?php 
    $followers = find_followers($id);

    foreach($followers as $follower){

        echo $follower->full_name() . "followed you.<br/>"; 
    }
    ?>