我有一个包含两个表的数据库,这两个表有#34;一对多"关系 第一个表名为带列的数据(姓名,电话,人格) 第二个表称为列链接(linkid,link,personid)。
Personid是forigne键,我想打印两个表(名称,电话,链接)中的3列,其中链接是每个用户链接。
所以我希望桌子是这样的:
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>";
表格如下:
姓名电话链接
John 67655 link1
link2
...
答案 0 :(得分:0)
您的查询应该像
SELECT data.personid, name, phone, link FROM data JOIN links ON data.personid = links.personid
然后在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'];
}
后来在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>";