在while循环中只回显mysql数据一次


echo mysql data only once in while loop

我已经设法进行了一次php聊天,每条消息都会在我的数据库表中得到一行,user_from列当然会多次相同。现在,我想回显发送给登录用户或来自登录用户的最新消息。我只能通过使用此代码来回显每条消息。

 <?php
  $select = mysql_query("SELECT * FROM privat_mess WHERE userid_to='$idn' OR      
  userid='$idn' ORDER BY identitet DESC");
 while($row = mysql_fetch_assoc($select)){
     $id = $row['identitet'];
     $userid = $row['userid'];
     $userid_to = $row['userid_to'];
     $user_from = $row['user_from'];
     $user_to = $row['user_to'];
     $msg_body = $row['msg_body'];
     $opened = $row['opened'];

    if($userid == $idn) {
    echo '<div class>
        <p><strong>'.$user_to.'</strong></p>
            '.$msg_body.'
    </div>';
    }
else{
        echo '<div>
        <p><strong>'.$user_from.'</strong></p>
          '.$msg_body.'
    </div>';
}
}
?>

$userid是发送消息的用户的users表中的$id,$idn是已登录用户的id。

我相信以某种方式使用unique_array((是可能的,但如果有人能告诉我如何使用,或者有更好的方法,我会非常感激。我也试着使用DISTINCT,但我无法让它正常工作。

我不希望它像脸书上的消息一样,顶部是最新的活跃聊天。如果你按下它,你就会进入聊天

编辑:

     $id = A_I, primary Key, the message id 
     $userid = the id for the user that sent the message 
     $userid_to = the id for the user that got the message 
     $user_from = name for the user who sent the message
     $user_to = name for the user who got the message
     $msg_body = The message text

我想显示每次聊天的最新消息。

我所说的一次聊天是指$userid和$user_from是唯一的。如果同一个用户发送了更多的消息,我不希望它们也被显示。

根据您的评论,但我希望每个用户有一条消息,而不是总共一条消息

试试这个:

SELECT 
     * 
FROM 
     privat_mess 
WHERE 
     userid_to='$idn' 
OR      
     userid='$idn' 
GROUP BY 
     userid
ORDER BY 
     identitet DESC
$select = mysql_query("SELECT * FROM privat_mess WHERE userid_to='$idn' OR      
                       userid='$idn' ORDER BY identitet DESC limit 0,1");

只会给你一张唱片,第一张。我建议您阅读限制一两分钟,因为它可以大大加快您的查询速度!

编辑:

好吧,如果你只想要一个解决方案,而不是一个花哨的解决方案(感觉我下班回家时离开了我的大脑(,只需拿出你想要的身份证,然后要求每一个:

SELECT 
      max(identitet), userid_from
FROM 
     privat_mess 
WHERE
     userid_to='$idn' OR userid='$idn'
GROUP BY userid_from

每次聊天你都会得到最新的身份信息,并且可以循环查看每个信息以获取更多信息。

如果你想从一开始就通过sql来解决这个问题,我有另一种方法,但它并不漂亮(不要在大数据库上使用它!(:

 SELECT * 
 FROM privat_mess 
 WHERE (userid_to='$idn' OR userid='$idn') AND 
 identitet IN (SELECT max(identitet) 
               FROM privat_mess
               WHERE userid_to='$idn' OR userid='$idn' 
               GROUP BY userid_from)