如何使用"一对多打印两个表的列"在html表中的关系?

时间:2017-09-29 08:18:14

标签: php html mysql sql pdo

我有一个包含两个表的数据库,这两个表有#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  
           ...

1 个答案:

答案 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>";