I have a table named as People:
id | name |parent_id
---+------+---------
1 | John | 0
2 | Jane | 1
3 | James| 1
4 | Jack | 0
5 | Jim | 4
6 | Jenny| 4
So john is parent of Jane and James. Tree goes like this.
John
-Jane
-James
Jack
-Jim
-Jenny
I want to make a table that seems like
<table border="1">
<tr>
<th colspan="2">John</th>
</tr>
<tr>
<td>-</td><td>Jane</td>
</tr>
<tr>
<td>-</td><td>James</td>
</tr>
<tr>
<th colspan="2">Jack</th>
</tr>
<tr>
<td>-</td><td>Jim</td>
</tr>
<tr>
<td>-</td><td>Jenny</td>
</tr>
<table>
To do this, I use two sql queries. Here is the pseudo-code:
<?php
$firstQuery = 'SELECT id, name FROM People WHERE parent_id = 0';
start creating the table
while ($rowP = $result_parent->fetch())
{
//get the child rows using the second query in the loop:
$secondQuery = 'SELECT id, name FROM People WHERE parent_id = $rowP["id"]';
start creating table rows for child items.
while ($rowC = $result_child->fetch())
{
add names into the table belonging the current parent person
}
}
?>
So the problem rises here.
This is very bad approach in the performance asppect. What is the correct way.
When I try to use the parent person's id as a parameter for the child people query, I get error about
bind_param()function.This can be done only one SQL query with
JOINoperation. But I don't know how to do.