F. Schulte F. Schulte - 1 year ago 56
PHP Question

How to show sql select parent and child in php

Maybe a simple question, but after hours of reading i still didn't find an answer.

I'm trying to get the values of subrow next to those of parent row, without constantly repeating parent row:

For example:

Table 1: ParentId = 1, ParentName = ParentName

Table 2:
ChildId = 1, ParentId = 1, ChildName = ChildName1

ChildId = 2, ParentId = 1, ChildName = ChildName2

The result with JOIN currently is:

ParentId, ParentName, ChildId, ChildName1
ParentId, ParentName, ChildId, ChildName2

But i would like to display the data like:

<div>Div with parent name</div>
<div>Div with ChildName1</div>
<div>Div with ChildName2</div>

<div>Div with parent name2</div>
<div>Div with ChildName1</div>
<div>Div with ChildName2</div>


Can anyone tell me how to get to this?

Something like

echo$Parent1 foreach child as $child echo$ChildName?

Answer Source

You can sort by parent ID, then check if it has changed. If it has changed output the name of the parent. Something like this:

$query = "query selecting data with join... ORDER BY ParentId";
$result = $mysqli->query($query);
$lastParent = 0;
while ( $row = $result->fetch_assoc($result) )
    if ( $row['ParentId'] != $lastParent )
        echo '<div>' . $row['ParentName'] . '</div>';
    $lastParent = $row['ParentId'];
    echo '<div>' . $row['ChildName'] . '</div>';

Using that the parent name will only output when the ID changes, and as we're ordering by ID all the children will be grouped by their Parent and output together.