我正在尝试使用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;
}
}
和用于获取结果的foreach循环
<?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
答案 0 :(得分:1)
在给定查询中,您似乎正在尝试从两个表 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'