I’m trying to create a parent-child relationship with mysql.
identifier |
parent_id |
Title |
contents |
---|---|---|---|
1 |
0 |
I’m parent #1 |
i’m happy for parent #1 |
2 |
0 |
i am parent no.2 |
i’m happy for parent #2 |
3 |
2 |
I am the child of parent no.2 |
i’m happy for parent #2 |
4 |
2 |
I am the child of parent no.2 |
im child content for parent #2 |
5 |
4 |
I am the grandchild of parent no.2 |
i am a content grandchild for parent #2 |
i am creating a parent table and child table separately but i was only able to create one level child so if i need to create a multi-nest child i have to create a new child table for each nested child…so after having done a bit research, I learned about Recursive function which I could create multiple nested children with without any problems.
Using PDO mysqli as below code
try {
$host="localhost";
$dbname="55";
$user="root";
$password = '';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$user,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
//$e->getMessage();
die("Something went wrong please contact your adminstrator");
}
function categoryTree($parent_id = 0, $sub_mark = '',$rt=""){
global $conn ;
$data = $conn->prepare("SELECT * FROM categories WHERE parent_id = :parent_id");
$data->bindParam(':parent_id', $parent_id);
$data->execute();
if ($data ->rowCount()) {
$i=1;
while($row = $data->fetch(PDO::FETCH_OBJ) ){
echo ''.$row->name.'';
categoryTree($row->id, $sub_mark.'-',$rt.'op');
$i++;
}
}
}
Number 1
Now the result is that all parents and children are in the same ‘li’(ul>li)
i want each child in the new ul>li with a unique id on li
i want title and content on tabs so i need unique id but it gives me same id for child title
//Tab-title
- im parent one
- im parent two arrow icon
-
im first child of parent two
-
im second child of parent two arrow icon
-
im garnd child of parent two
-
im garnd child of parent two
The span tag should only be displayed if they have a child, if the parent has a child and the child has a grandchild, the span tag should be displayed only in the parent and the child, if the parent n ‘has no children, the span tag should not be displayed
Number 2
Now in tab content parent content should only be displayed if it has child, if parent has child only child content should be displayed but if parent has grandchild , only grandchild content should be displayed… in content tabs only last child content should be displayed.
I easily achieved these options by creating a parent and child table separately, but with a recursive function creating a single table, I’m not able to meet my needs