I have 2 tables in a MariaDB
Table 1 structure:
ID (primary auto-increment) itemType(ENUM) and itemName(varchar)
The ENUM has 4 possibilities - "heading","section","text","citation".
Table 2 structure
ID (primary auto-increment) TID(int) parentID(int) and childID(int)
though it's possible I may need another column to perform the recursion.
Table 1 contains the text, and Table 2 the relationships of the text to each other.
The purpose of the query is to produce a nested JSON array/object in a tree structure.
example:[{itemType:"heading",sub[{itemType:"section",sub:[{itemType:"text"},{itemType:"text"},{itemType:"text"},{itemType:"text"}]},{itemType:"section",sub:[{itemType:"text"},{itemType:"text"}]} ]}]
so it can produce an HTML tree such as
- Heading 1
- Section 1
- Text 1
- Text 2
- Text 3
- Text 4
- Section 2
- Text 2
- Text 4
- Section 1
- Heading 2
- Section 2
- Text 1
- Text 3
- Section 3
- Text 2
- Text 4
- Text 5
- Text 6
- Section 2
Problems A heading can only exist once in the list Sections and text can appear many times in the whole list but only once within each heading Sections can be a child of any header so it's not "tied" Text can be a child of any section so it's not "tied"
So I start with
$data = $pdo->query("SELECT * FROM items WHERE itemType = 'header' ")->fetchAll();
The loop through $data
foreach( $data as $row ){writeMessage( $row['ID'],$row['ID']);}
Where writeMessage() is my recursive function
function writeMessage($ID, $TID){
global $pdo;
$stmt = $pdo->query("SELECT * FROM testing LEFT JOIN items ON items.ID = '$ID' WHERE parentID = '$ID' AND TID = '$TID' ");
while ($row = $stmt->fetch()) {
echo $row['ID'].' '.$row['itemName'].' '.$row['childID'].'<br/>';
writeMessage($row['childID'],$TID);
}
}
But I never get the right results.
Help and suggestions please, it's along time since I used PHP in this way