[英]Join Two MySQL Table and Display Result in Table
I have two table called t_user and t_chat. 我有两个表,分别称为t_user和t_chat。 I am trying to display message from t_chat in PHP table like below. 我正在尝试在PHP表中显示来自t_chat的消息,如下所示。
$quotes_qry="SELECT * FROM t_chat ORDER BY id DESC LIMIT $start, $limit";
$result=mysqli_query($mysqli,$quotes_qry);
<?php
$i=0;
while($row=mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo ++$sr+$start;?></td>
<td><?php echo $row['sender'];?></td>
<td><?php echo nl2br($row['receiver']);?></td>
<td><?php echo nl2br($row['message']);?></td>
<td><?php echo time_elapsed_string($row['time']);?></td>
<td><a href="?id=<?php echo $row['id'];?>" class="" onclick="return confirm('Are you sure you want to delete this row?');"><img src="images/delete-icon.png"></a></td>
</tr>
<?php
$i++;
}
?>
I want display sender and receiver name which is located in table called t_user with username column
. 我想要显示名为t_user with username column
表中t_user with username column
名列的发送方和接收方名称。 I am new in PHP and confused how can I achieve it. 我是PHP新手,对如何实现它感到困惑。 Let me know if someone can help me for achieve my task. 让我知道是否有人可以帮助我完成任务。 Thanks a lot! 非常感谢!
Note : t_chat table have userid witch column name called sender and receiver, currently I am displaying that userid in above table, instead I want display username. 注意:t_chat表具有名为发件人和接收者的用户名列名称,当前我在上表中显示该用户名,而不是显示用户名。 Thanks 谢谢
The joins might look something like this: 联接可能看起来像这样:
SELECT t_chat.sender AS 'sender', t_chat.receiver AS 'receiver', t_chat.message AS 'message', t_chat.time AS 'time', t_chat.id AS 'id', user1.username AS 'senderusername', user2.username AS 'receiverusername'
FROM t_chat
LEFT JOIN t_user AS user1 ON t_chat.sender = user1.id
LEFT JOIN t_user AS user2 ON t_chat.receiver = user2.id
ORDER BY id DESC
In this example I am joining the tables twice (as user1 and user2) so that the t_user
table gets referenced independently for each lookup. 在此示例中,我两次将表t_user
(分别作为user1和user2),以便为每个查找独立引用t_user
表。
I also gave each column a name using AS
to make them easier to reference later in your code. 我还使用AS
为每列命名,以使它们在以后的代码中更易于引用。
Try this sql (The t_user table must have an id
column that matches the userid
from t_chat): 尝试以下sql(t_user表的id
列必须与t_chat中的userid
匹配):
$quotes_qry="SELECT t1.sender, t1.receiver, t1.message, t1.time, t2.username FROM t_chat AS t1 INNER JOIN t_user AS t2 ON t1.userid=t2.id ORDER BY t1.id DESC LIMIT $start, $limit";
More details and examples about MySQL JOIN you can find in the tutorial from: 您可以在本教程中找到有关MySQL JOIN的更多详细信息和示例,网址为:
https://coursesweb.net/php-mysql/mysql-inner-left-join-right-join_t https://coursesweb.net/php-mysql/mysql-inner-left-join-right-join_t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.