获取新闻Feed(社交媒体)

时间:2018-05-21 02:07:57

标签: php mysql

我目前正在开发一个社交媒体应用,其中包括用户(您可以将其添加为好友)和帖子(文字,图片等...)

与用户的帖子和用户的朋友相比,我希望向用户显示5个最新帖子'用户进入应用时的帖子。

我知道这不是最明智的方法,但到目前为止我做到了这一点。 查询只返回一个帖子,但有更多,甚至不是最新的也不是最旧的。我认为问题出现在" OR"子句。

我得到了所有sno用户的朋友,然后用" OR"逐个放入WHERE子句。子句。

        where any of the following is true:
            - this housing period is a college housing period
            - this housing period is an internship housing period,

用户的sno为1,用户有两个朋友,他们的sno是2和75.

echo $ sql;

        //CURRENT FRIENDS
        $sql = 'SELECT current AS currents FROM friends WHERE sno = :sno';
        $query = $this -> conn -> prepare($sql);
        $query -> execute(array(':sno' => $usersSno));

        $friends = $query -> fetchObject() -> currents;

        //SELECT 5 NEWEST POST
        $sql = 'SELECT operationId FROM posts WHERE operationId = :operationId';
        $array = array(':operationId' => $usersSno);

        if(isset($friends)) {
            $ids = explode(",", $friends);
            for($i = 0; $i < count($ids); $i++) {
                $sql = $sql.' OR operationId = :operationId'.$i;
                $array[':operationId'.$i] = $ids[$i];
            }
        }

        if($from == null)
            $sql = $sql.' ORDER BY operationId DESC LIMIT 5';
        else {
            $sql = $sql.' AND operationId < :from ORDER BY operationId DESC LIMIT 5';
            $array[':from'] = $from;
        }

        $query = $this -> conn -> prepare($sql);
        $query -> execute($array);
        $result = $query -> fetchAll(PDO::FETCH_ASSOC);

的print_r($阵列);

SELECT operationId FROM posts WHERE operationId = :operationId OR operationId = :operationId0 OR operationId = :operationId1 ORDER BY operationId DESC LIMIT 5

1 个答案:

答案 0 :(得分:7)

我觉得在开始赏金之后立即意识到我的错误是一种愚蠢。我应该使用WHERE sno(因为我一直在WHERE operationId

获取用户ID [sno]的帖子而不是$sql

所以echo $sql;就像:

SELECT operationId FROM posts WHERE sno = :sno OR sno = :sno0 OR sno = :sno1 ORDER BY operationId DESC LIMIT 5

print_r($array)是:

Array
(
    [:sno] => 1
    [:sno0] => 2
    [:sno1] => 75
)

至少我很乐意解决这个问题,甚至自己解决这个问题:)

  

编辑:我在sql查询中也发现了两个逻辑错误。

1-将日期字符串与post 的operationId进行比较   我将帖子与他们的日期进行比较(你也可以比较post的operationId)来看看哪一个是最新的。但是在代码中我将operationId与$from变量(日期字符串)进行了比较。

最终代码;

$sql = $sql.') AND createdAt < :from ORDER BY operationId DESC LIMIT 5';

2- OR条款应与括号中的AND子句分开。

开始括号

$sql = 'SELECT operationId FROM posts WHERE (sno= :sno';

括号结束

if($from == null)
    $sql = $sql.') ORDER BY operationId DESC LIMIT 5';
else {
    $sql = $sql.') AND createdAt < :from ORDER BY operationId DESC LIMIT 5';
    $array[':from'] = $from;
}