在 select 查询中使用变量

Using a variable in a select query

问题
我正在尝试创建一个网站,用户可以在其中 post post,然后他们的朋友可以看到这些 post。类似于 facebook、twitter 等
我已经到了用户可以成为朋友并且他们可以 post 东西的地步。但是,我无法将显示的 post 限制为用户朋友的 post。目前每个用户都可以看到每个 post.
我在 MVC 架构中使用 PDO。

数据库结构

TABLE `friends` (
    `friendship_id` int(11) NOT NULL AUTO_INCREMENT,
    `user_one` int(11) NOT NULL,
    `user_two` int(11) NOT NULL,
    PRIMARY KEY (`friendship_id`),
    FOREIGN KEY (user_one) REFERENCES users(user_id),
    FOREIGN KEY (user_two) REFERENCES users(user_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


在上面的table中,根据谁向谁发送了好友请求,'user_one'可以是我自己或我的朋友,或者'user_two'可以是我自己或我的朋友。

TABLE `posts` (
 `post_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `post_text` text NOT NULL,
 `user_id` int(11) unsigned NOT NULL,
 PRIMARY KEY (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


模特

    /**
     * Get all posts from the suer's friends
     * @return array an array with several objects (the posts)
     */
    public static function getAllPosts()
    {   
        $my_id = Session::get('user_id');

        $database = DatabaseFactory::getFactory()->getConnection();

        // get all of the user's friends
        $friendsQuery = $database->prepare("
                                    SELECT user_one FROM friends WHERE user_two = '$my_id';
                                    SELECT user_two FROM friends WHERE user_one = '$my_id';
                                    ");

        $friendsQuery->execute();
        $friends = $friendsQuery->fetchAll();
        $friendsQuery->closeCursor();

        $query = $database->prepare("SELECT * FROM posts WHERE user_id = '$my_id' OR user_id = '$friends'");
        $query->execute(array());

        return $query->fetchAll();
    }


在上面的代码中,我的问题在于 $friends 变量。如果我用我朋友的 user_id 手动替换它,它会按预期工作。
例如:

"SELECT * FROM posts WHERE user_id = '$my_id' OR user_id = '1'"; 

控制者

    /**
     * Gets all posts (of the user and his friends).
     */
    public function index()
    {
        $this->View->render('post/index', array(
            'posts' => PostModel::getAllPosts()
        ));
    }

景色

       <?php if ($this->posts) { ?>
            <?php foreach($this->posts as $key => $value) { ?>
                <p><?= htmlentities($value->post_text); ?></p>
            <?php } ?>
        <?php } ?>


总结
我无法创建一个 sql 查询,它只是 selects posts,由我自己或我的朋友 posted 而不是 select任何其他 post。

如果有人能帮我解决这个问题,我将不胜感激!




更新
我的模型现在看起来像这样:

    /**
     * Get all posts from the suer's friends
     * @return array an array with several objects (the posts)
     */
    public static function getAllPosts()
    {   
        $my_id = Session::get('user_id');

        $database = DatabaseFactory::getFactory()->getConnection();

        // get all of the user's friends
        $friendsQuery = $database->prepare("
                                    SELECT user_one FROM friends WHERE user_two = '$my_id';
                                    SELECT user_two FROM friends WHERE user_one = '$my_id';
                                    ");

        $friendsQuery->execute();
        $friends = $friendsQuery->fetchAll();
        print_r($friends);
        $friendsQuery->closeCursor();

        foreach($friends as $friend)
        {
            $friend_ids[$friend->key] = $friend->val;
        }
        print_r($friend_ids);
        $friendsSQL = implode(',',$friend_ids);

        $query = $database->prepare("SELECT * FROM posts WHERE user_id = '$my_id' OR user_id IN('$friendsSQL')");
        $query->execute();

        return $query->fetchAll();
    }


这是我的输出:

Array ( [0] => stdClass Object ( [user_one] => 1 ) )

Notice: Undefined property: stdClass::$key

Notice: Undefined property: stdClass::$val

Array ( [] => )

您可以将所有 friends_id 添加到一个数组中,然后使用此代码。

//$friends is an array.
$friendsSQL = implode(',',$friends);
$query = $database->prepare("SELECT * FROM posts WHERE user_id = '$my_id' OR user_id IN($friendsSQL)");

您应该注意 $friendsQuery->fetchAll() 将 return 一个数组。此外,如果 PDO::FETCH_ASSOC 作为附加参数提供 [fetchAll(PDO::FETCH_ASSOC)],它将是一个关联数组。

数组的结构可以如下所示:

Array ( [int] datasetNumber =>
    Array (
       [string] "friendship_id" => [int] 1,
       [string] "user_one"      => [int] 1,
       [string] "user_two"      => [int] 1       
    )
) 

我在 this post.

中提供了一些关于 return 从 PDO 语句中获取数据的更多信息

您的 $friends 变量由 fetchAll() 函数返回,因此可能是一个结果列表。然后您将该列表用作查询中的字符串,这是行不通的。您需要从 $friends 列表中提取好友的 ID。

如果您正在使用 PDO,那么请使用 PDO 中内置的变量处理,即:

$query = $database->prepare("SELECT * FROM posts WHERE user_id = :variable_ID OR user_id = '1'");
$query->bindValue( ':variable_ID', $my_id, PDO::PARAM_STR ] );
$query->execute();