[英]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是發送消息的用戶的用戶表中的$ id,$ idn是已登錄用戶的ID。
我確定可以以某種方式使用unique_array(),但如果有人可以向我展示如何或是否有更好的方法,我將非常感謝。 我也嘗試使用DISTINCT,但無法使其正常工作。
我不希望它像Facebook上的消息一樣,其中最重要的是最新的活動聊天。 如果按下它,您將進入該聊天
編輯:
$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");
只會給你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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.