【发布时间】:2014-08-05 12:09:38
【问题描述】:
我已经设法进行了一个 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 是唯一的。如果同一用户发送了更多消息,我不希望它们也显示出来。
【问题讨论】:
-
一旦你想退出循环就使用
break; -
注意:您正在使用的
mysql_*函数已被弃用,并将在未来的 PHP 版本中删除。不要使用它们编写新代码,而是使用mysqli_*或 PDO。 -
只需将
LIMIT 1添加到您的查询中,结果只会得到 1 行。 -
好的,谢谢,杰拉德我会记住这一点。 JiFus,我试过了,但是我总共只收到一条消息,我想要每个聊天中的一条消息
-
我想从每个聊天中得到一条消息你是什么意思?请向我们展示您的表结构
标签: php mysql while-loop