php - 由于查询,人们在聊天页面上显示了两次
问题描述
我正在尝试使用 php 制作一个 facebook 风格的聊天页面。但是我在显示旧对话时遇到了问题。您知道 facebook 左侧边栏显示对话,当您创建新消息时,用户可以在他的消息页面上看到您的消息。问题:当我向某人发送消息时,他们从左侧边栏中看到我的消息两次。我也从左侧边栏中看到我的消息两次。
我创建了这个SQLfiddle
所以这是我的查询功能:
public function ChatUserList($uid){
$uid = mysqli_real_escape_string($this->db,$uid);
$ChatUserListQuery = mysqli_query($this->db,"SELECT DISTINCT C.to_user_id,
C.from_user_id,U.user_name, U.user_fullname
FROM chat C INNER JOIN users U
ON U.userid = C.from_user_id WHERE U.userid = '$uid'
AND (C.from_user_id = '$uid' OR C.to_user_id = '$uid')")
or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($ChatUserListQuery)) {
// Store the result into array
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
}
注意:$uid
是登录的用户 ID。喜欢$uid = '2';
我像这样在屏幕上打印它。
$ConversationUserList = $Get->ChatUserList($uid);
if($ConversationUserList){
foreach($ConversationUserList as $cData){
$conversationUserID = $cData['to_user_id'];
$conversationUserAvatar = $Get->UserAvatar($conversationUserID, $base_url);
$conversationLastMessage = $Get->ChatLastMessage($uid,$conversationUserID);
$conversationUserFullName = $Get->UserFullName($conversationUserID);
$conversationUserName = $Get->GetUserName($conversationUserID);
if($conversationUserID == $uid){
$conversationUserID = $cData['from_user_id'];
$conversationUserAvatar = $Get->UserAvatar($conversationUserID, $base_url);
$conversationLastMessage = $Get->ChatLastMessage($uid,$conversationUserID);
$conversationUserFullName = $Get->UserFullName($conversationUserID);
$conversationUserName = $Get->GetUserName($conversationUserID);
}
$time = $conversationLastMessage['message_created_time'];
$conversationLastMessageTime = date("c", $time);
$getConversationLastMessage = $conversationLastMessage['message_text'];
echo '
<!---->
<li class="_5l-3 _1ht1 _1ht2 getuse" data-id="'.$conversationUserID.'" data-user="'.$conversationUserName.'">
<img src="'.$conversationUserAvatar.'" class="img_avatar">
<span>
<abbr class="_1ht7 timeago" id="time'.$conversationUserID.'" title="'.$conversationLastMessageTime.'">
'.$conversationLastMessageTime.'</abbr>
</span>
<span class="_1qt5 _5l-3">
<span class="txt_st12" id="msg'.$conversationUserID.'">
'.htmlcode($getConversationLastMessage).'
</span>
</span>
</li> ';
}
}
解决方案
该行为是正常的,但您应该限制为 1 并按时间排序以选择最近的消息。
同样在您的 SQL 小提琴中,我猜您正在从用户到用户混淆。
推荐阅读
- cordova - 如何使threejs画布不被键盘调整大小
- c# - C# WindowsForms PictureBox:控制坐标和图像中像素位置之间的转换
- c# - 为什么不调用这个 C# 实例构造函数,除非有对非静态成员的引用?
- javascript - 要使用数组值更新的对象值
- angular - Angular 材质每 2 个字符后添加分号
- java - 将 .txt 文件转换为一个 .csv。导出的信息会覆盖第一行。有小费吗?
- r - R data.table 到 xts 与分组
- prestashop - Prestashop 自定义页面与自己的模板
- python - 使用随机森林回归(或其他集成模型)时如何消除回归变量/系数的影响
- python - VideoCapture() 读取多个视频和帧分辨率问题