It have two table parent table and children table
Parent Table
id page-title page-content
Children Table (where parent_id = id) id from parent table
child_id parent_id child-title child-content
Now How to find out if parent have any children
<?php
//parent table
$data = $conn->query("SELECT * FROM parent_page ORDER BY id DESC");
while($rows = $data->fetch(PDO::FETCH_OBJ) ):
$parent_id = $rows->id;
?>
<?php
//chlidren table
$child_data= $conn->query("SELECT * FROM children_page WHERE parent_id = $parent_id ");
while($child_rows = $child_data->fetch(PDO::FETCH_OBJ) ):
$child_rows->parent_id;
?>
<?php
//requirement check if parent have children (how to check if parent have children or not)
if('parent have children'){
then echo children content;
}else{
echo parent content;
}
?>
<?php endwhile; endwhile;?>
CodePudding user response:
Get the number of rows in the child query. If it's more than zero, the parent has children.
You should also use a prepared query instead of substituting variables directly into the SQL.
<?php
$child_data = $conn->prepare("SELECT * FROM children_page WHERE parent_id = :parent");
$child_data->bindParam(':parent', $parent_id);
//parent table
$data = $conn->query("SELECT * FROM parent_page ORDER BY id DESC");
while($rows = $data->fetch(PDO::FETCH_OBJ) ):
$parent_id = $rows->id;
?>
<?php
//chlidren table
$child_data->execute();
if ($child_data->rowCount()) {
// parent has children
while($child_rows = $child_data->fetch(PDO::FETCH_OBJ) ):
// echo children content
?>
<?php endwhile;
}else{
echo parent content;
}
?>
<?php endwhile;?>
CodePudding user response:
I Have no idea in PHP. But you can do this by changing your query.
Select *
from Children c
left Join Parent p on p.id = c.parent_id
You can check parent_id value.
If Parent_id value null then no parent avaialble. If it is not null parent is Available.
CodePudding user response:
hp //chlidren table $child_data= $conn->query("SELECT * FROM children_page WHERE parent_id = $parent_id "); while($child_rows = $child_data->fetch(PDO::FETCH_OBJ) ): $child_rows->parent_id; ?>