php查询函数重复数据

laik7k3q  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(343)

我正在尝试使用php和mysql制作一个facebook风格的聊天页面。但是我的查询结果有问题。聊天桌是这样的。

我编写了这个函数来获取登录用户的消息。

/*Get Messges*/
public function Get_Messages($toid,$logedInUserID){
   // Here is loged in user id the id is 2
   $logedInUserID = mysqli_real_escape_string($this->db,$logedInUserID);
   // Loged in user id talked with $toid before the id is 3
   $toid = mysqli_real_escape_string($this->db,$toid);
   $logedInUserID = '2';  
   $toid = '3';

   $query = mysqli_query($this->db,"SELECT DISTINCT C.msg_id,C.from_user_id, C.to_user_id, C.message_created_time, C.message_text, U.user_name, U.user_fullname FROM users U, chat C WHERE C.from_user_id='$logedInUserID' AND C.to_user_id = '$toid' ORDER BY C.msg_id ASC LIMIT 20") or die(mysqli_error($this->db));
   while($row=mysqli_fetch_array($query,MYSQLI_ASSOC)) {
        // Store the result into array
        $data[]=$row;
     }
     if(!empty($data)) {
        // Store the result into array
        return $data;
     }
}

以及得到结果的前循环

<?php 
    $GetAllMessages = $Get->Get_Messages($toUserID,$uid);
     if($GetAllMessages){
         echo '<span class="all_messages">';
      foreach($GetAllMessages as $getMessage){
         $getTexts = $getMessage['message_text']; 
         $getToUID = $getMessage['to_user_id']; 
         $from_to_class= 'you';
         if($getToUID == $uid){
             $from_to_class = 'friend';
         } 
         echo '<div class="messageBox_body"><div class="'.$from_to_class.'">'.$getTexts.'</div></div>';
       }
         echo '</span>';
      } 
?>

所以问题是我的查询重复了如下屏幕截图所示的消息,而且查询没有显示登录的用户消息。
更具描述性的是:

$logedInUserID = '2';
$toid = '3';

查询显示 $toid = '3'; 重复且不显示的消息 $logedInUserID = '2'; 从数据中。
我的问题是什么:

SELECT DISTINCT C.msg_id,C.from_user_id, C.to_user_id, C.message_created_time, 
C.message_text, U.user_name, U.user_fullname FROM users U, chat C WHERE 
C.from_user_id='$logedInUserID' AND C.to_user_id = '$toid' 
ORDER BY C.msg_id ASC LIMIT 20

wnrlj8wa

wnrlj8wa1#

在给定的查询中,您似乎试图从两个表user和chat中获取详细信息,但是您还没有编写连接条件。
请使用$logedinuserid='2'尝试此sql查询$toid='3';

SELECT DISTINCT C.msg_id, 
                C.from_user_id, 
                C.to_user_id, 
                C.message_created_time, 
                C.message_text, 
                U.user_name, 
                U.user_fullname 
FROM   users U 
       JOIN chat C 
         ON U.id = C.from_user_id 
WHERE  C.from_user_id = '$logedInUserID' 
       AND C.to_user_id = '$toid' 
ORDER  BY C.msg_id ASC 
LIMIT  20

如果您想与两个用户进行整个聊天,只需在sql查询中使用“or”条件,交换$logedinuserid='3'$toid='2'

相关问题