它有兩個表父表和子表
父表
id page-title page-content
子表(其中 parent_id = id)來自父表的 id
child_id parent_id child-title child-content
現在如何確定父母是否有孩子
<?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;?>
uj5u.com熱心網友回復:
獲取子查詢中的行數。如果大于零,則父母有孩子。
您還應該使用準備好的查詢,而不是將變數直接替換到 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;?>
uj5u.com熱心網友回復:
我對PHP一無所知。但是您可以通過更改查詢來做到這一點。
Select *
from Children c
left Join Parent p on p.id = c.parent_id
您可以檢查 parent_id 值。
If Parent_id value null then no parent avaialble. If it is not null parent is Available.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/496280.html
標籤:mysql
上一篇:咨詢注冊Mysql
