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).
2nd table called links with columns(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 .
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
link2
...
Your query should be like
SELECT data.personid, name, phone, link FROM data JOIN links ON data.personid = links.personid
Then in 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:
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>";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.