7
I’m putting together a system of infinite categories and subcategories, simple to begin with. I found a script on the internet that meets the requirements, but its customization and adaptation to my project made it almost unusable.
I studied a simple structure and adapted the database and the registration script correctly, but my biggest problem is being in the display part.
Based on the following records:
Listing in the way I adapted (considering incorrect) I have some limitations because when it comes to children of subcategories already children are not listed, I need a simple script that does such a procedure and is easy to customize.
Currently I have the following result:
My script for current listing:
<?php
echo "<ul>";
$selCategorias2 = $conn->prepare("SELECT * FROM cat WHERE cat_pai = ?");
$selCategorias2->execute(array(0));
while($rowCategoria2 = $selCategorias2->fetch(PDO::FETCH_OBJ)){
echo $rowCategoria2->cat_nome."<BR/>";
$selFilhos = $conn->prepare("SELECT * FROM cat WHERE cat_pai = ?");
$selFilhos->execute(array($rowCategoria2->cat_id));
while($rowFilho = $selFilhos->fetch(PDO::FETCH_OBJ)):
echo " ".$rowFilho->cat_nome."<br/>";
$selSubFilhos = $conn->prepare("SELECT * FROM cat WHERE cat_pai = ?");
$selSubFilhos->execute(array($rowFilho->cat_id));
while($rowSubFilho = $selSubFilhos->fetch(PDO::FETCH_OBJ)):
echo " ".$rowSubFilho->cat_nome."<br/>";
endwhile;
endwhile;
} //fecha while categoria raiz
echo "</ul>"; ?>
Note: I know there are other ways to space the category besides " " however, in this case it is only for testing.
The script I quoted earlier uses FETCH_ASSOC instead of FETCH_OBJ
I would not be so vehement in indicating nested sets. Depending on the desired use, it can be a great idea or a bad idea. In my personal experience, it depends a lot on the use case.
– bfavaretto
+1 anyway by documenting the variety of possible solutions with pure Mysql.
– bfavaretto
Unfortunately there is no perfect solution to this case, because of the very concept of relational database. I ended up adding another solution besides the nested model, had forgotten the closure table.
– Erico
As for Managing Hierarchical Data in Mysql, I found it really interesting because it deals only with queries in pure SQL, but in some cases it becomes a somewhat limited way depending on the amount of levels desired, but it is a viable alterantiva according to each project.
– Tiago Boeing