[英]mysqli query echo data from two tabels
I have two tables:我有两个表:
bb_users ( user_id, user_name, user_password .... )
bb_topics ( id, time, topic, sender, reciever)
sender
and reciever
are related to user_id
in the bb_users
table. sender
和reciever
涉及user_id
在bb_users
表。 For example, sender 450 = user_id 450 = user_name
"demouser".例如,
sender 450 = user_id 450 = user_name
"demouser"。
When I export the data from the tables, I want to replace receiver
and sender
with their user_name
.当我从表中导出数据时,我想用他们的
user_name
替换receiver
和sender
。
<?php
$con=mysqli_connect("$DB_HOST","$DB_USER","$DB_PASS","$DB_NAME");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,' SELECT * FROM bb_topics LIMIT 3000');
echo "<table border='1'>
<tr>
<th>id</th>
<th>time</th>
<th>topic</th>
<th>sender</th>
<th>receiver</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "<td>" . $row['topic'] . "</td>";
echo "<td>" . $row['sender'] . "</td>";
echo "<td>" . $row['receiver'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The export looks like:导出看起来像:
id | time | topic | sender | receiver
1 | 1580471226 | demo topic | 320 | 150
user_id
of sender 320
, his user_name
in bb_users
= "demotest", receiver
= "demo2". user_id
的sender 320
,其user_name
在bb_users
= “demotest”, receiver
= “DEMO2”。
I used LIMIT 3000
because there is a lot of data to be exported.我使用了
LIMIT 3000
因为有很多数据要导出。 Sometimes I got a PHP fatal error.有时我会遇到 PHP 致命错误。
How can I convert sender
and receiver
to their real username, and how to convert time from timestamp to date?如何将
sender
和receiver
转换为他们的真实用户名,以及如何将时间从时间戳转换为日期?
I would advise a more complex SQL Query.我建议使用更复杂的 SQL 查询。
Example: http://sqlfiddle.com/#!9/df5e0e8/14/0示例: http : //sqlfiddle.com/#!9/df5e0e8/14/0
SELECT t.id, FROM_UNIXTIME(t.time, "%Y-%m-%d %H:%i:%s") AS time, t.topic, u1.user_name AS sender, u2.user_name AS receiver
FROM bb_topics AS t
LEFT JOIN bb_users AS u1 ON u1.user_id = t.sender
LEFT JOIN bb_users AS u2 ON u2.user_id = t.receiver;
The output would be:输出将是:
| id | time | topic | sender | receiver |
|----|---------------------|------------|----------|----------|
| 1 | 2020-01-31 11:47:06 | demo topic | hsimpson | msimpson |
You can also send the Epoch Time to JavaScript if you want.如果需要,您还可以将 Epoch Time 发送到 JavaScript。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.