[英]How to print columns of two tables with “one to many” relationship in an html table?
I have a database with two tables and the two tables have "one to many " relationship . 我有一个包含两个表的数据库,并且两个表具有“一对多”关系。
1st table called data with columns(name , phone , personid). 第一个表称为带有列(名称,电话,个人ID)的数据。
2nd table called links with columns(linkid , link , personid). 第二个表称为带有列的链接(linkid,link,personid)。
Personid is the forigne key , I want to print 3 columns from the two tables (name , phone , links) where links is each user links . Personid是Forigne键,我想从两个表(名称,电话,链接)中打印3列,其中links是每个用户的link。
So I want the table to be something like that : 所以我希望桌子是这样的:
echo "<table>";
echo "<tr><th>Name</th> <th>Phone</th> <th>Links</th></tr>";
while ($row = $result->fetchAll(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['phone']."</td>";
echo "<td>".$row['links']."</td>";
echo "</tr>";
}
echo "</table>";
And the table looks like that : 桌子看起来像这样:
Name Phone Links 命名电话链接
John 67655 link1 约翰67655 link1
link2
...
Your query should be like 您的查询应该像
SELECT data.personid, name, phone, link FROM data JOIN links ON data.personid = links.personid
Then in PHP: 然后在PHP中:
$data = [];
foreach($results as $result) {
if (!isset($data[$result['personid']])) {
$data[$result['personid']] = [
'name' => $result['name'],
'phone' => $result['phone'],
'links' => [],
];
}
$data[$result['personid']]['links'][] = $result['link'];
}
And later in HTML: 然后在HTML中:
echo '<table>';
foreach ($data as $row) {
echo "<tr>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['phone']."</td>";
echo "<td>".implode(', ', $row['links'])."</td>";
echo "</tr>";
}
echo "</table>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.