我有这个为用户存储消息的表。它有id(PK), username, message, time, date
。当你登录你的账户时,它会显示你所有聊天记录的列表。但是这个DB只显示消息。我是否必须创建另一个表,以某种方式连接到第一个DB或过滤器,以便获得与我聊天的人的用户名?我获得用户名的意思是,我有我发过消息的人的列表。有什么办法能让我拿到用户名吗?
顺便说一下,代码如下:
<div id='messages'>
<nav>
<ul id=''>
<?php
$m = new mysqli('localhost', 'root', 'xamppprogram', 'blue_messenger');
if($m === FALSE){
include('./errordb2.php');
die();
}
$sql = "SELECT * FROM messages WHERE username='$username'";
$results = $m->query($sql);
if($results->num_rows > 0){
while($r = $results->fetch_assoc()){
// What to do here?
}
} else {
echo "No new messages.";
}
?>
<ul>
<nav>
</div>
<div id='chat-content'>
您可以在表中添加另一列,例如toUser
,它存储与您聊天的用户的名称。然后,您可以在sql中使用GROUP BY toUser
条件。这将是最简单的解决方案,但正如其他人在问题的评论中所述,关系数据库将是最好的解决方案。
您最好使用准备好的语句,因为这里似乎使用了用户输入,并且可能会导致SQL注入。
引用:
- https://en.wikipedia.org/wiki/Prepared_statement
- https://en.wikipedia.org/wiki/SQL_injection