首页 > 解决方案 > 由于查询,人们在聊天页面上显示了两次

问题描述

我正在尝试使用 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> ';
                   }
              } 

标签: phpmysqlsql

解决方案


该行为是正常的,但您应该限制为 1 并按时间排序以选择最近的消息。

同样在您的 SQL 小提琴中,我猜您正在从用户到用户混淆。


推荐阅读