0

我正在开发一个“集体帖子”页面,您的所有朋友的帖子都会出现在该页面上。我不是在谈论,$_POST而是在 facebook 上发布状态更新之类的帖子。我的代码有些作用,但唯一的问题是它返回了三个以上的结果,我不知道为什么。我环顾四周,但我没有任何运气。

编码:

        $my_id = $_SESSION['user_id'];
        $frnd_query = mysql_query("SELECT user_one, user_two FROM friends WHERE user_one='$my_id' OR user_two='$my_id'");
        while($run_frnd = mysql_fetch_array($frnd_query)) {
            $user_one = $run_frnd['user_one'];
            $user_two = $run_frnd['user_two'];
            if($user_one == $my_id){
                $user = $user_two;
            } else {
                $user = $user_one;
            }



              $res=mysql_query("SELECT * FROM posts WHERE user_id=$user ORDER BY timestamp DESC LIMIT 0, 3");

              while($row=mysql_fetch_assoc($res)) {
                ?>
                    <div class="span4">
                      <h3><a href="<?php echo username_from_user_id($user); ?>"><?php echo first_name_from_user_id($user), ' ', last_name_from_user_id($user) ?></a></h3>
                       <h8><?php echo date('F j, Y', strtotime($row['timestamp'])) ,' at ', date('h:i A', strtotime($row['timestamp'])); ?></h8>
                      <p><?php echo $row['content']; ?></p>
                      <p><a class="btn" href="#">View Reactions &raquo;</a></p>
                    </div><!--/span-->

                <?php
              }



        }//While Run_frnd

        ?>

我尝试了很多东西,但没有运气。另外,当涉及到新的 PDO 时,我该怎么办?

4

2 回答 2

1
SELECT *
FROM posts p
JOIN (SELECT user_one AS user_id
      FROM friends
      WHERE user_two = '$my_id'
      UNION DISTINCT
      SELECT user_two AS user_id
      FROM friends
      WHERE user_one = '$my_id') u
USING (user_id)
ORDER BY timestamp DESC
LIMIT 3

看我的小提琴

于 2013-03-29T19:40:05.683 回答
0

这个查询:

mysql_query("SELECT * FROM posts WHERE user_id=$user ORDER BY timestamp DESC LIMIT 0, 3")

正在此while循环中运行:

while($run_frnd = mysql_fetch_array($frnd_query)) {

因此,每个朋友最多可以获得 3 个结果,而不是总共 3 个结果。

您可以通过以下方式解决它:

$res=mysql_query("SELECT * FROM posts WHERE user_id=$user ORDER BY timestamp DESC LIMIT 0, 3");

while($row=mysql_fetch_assoc($res)) {

  $i = !isset($i) ? 1 : $i + 1;

    ?>
                <div class="span4">
                  <h3><a href="<?php echo username_from_user_id($user); ?>"><?php echo first_name_from_user_id($user), ' ', last_name_from_user_id($user) ?></a></h3>
                   <h8><?php echo date('F j, Y', strtotime($row['timestamp'])) ,' at ', date('h:i A', strtotime($row['timestamp'])); ?></h8>
                  <p><?php echo $row['content']; ?></p>
                  <p><a class="btn" href="#">View Reactions &raquo;</a></p>
                </div><!--/span-->

    <?php

  if (3 == $i)
  {
    break 2;
  }  

}
于 2013-03-29T19:34:19.143 回答