Jump to content

[SOLVED] Displaying product categories


fooDigi

Recommended Posts

is there a more efficient way?

i have a hierarchy of product categories... in the db table, each has an ID, Name, and ParentID, like so...

 

ID|Name|ParentID

_________________

1|Home & Garden|0

2|Books|0

3|Kitchen & Dining|1

4|Bedding & Bath|1

5|Textbooks|2

6|Magazines|2

etc ... and they go about 5 levels deep right now, but theoretically could go much much deeper

 

a '0' ParentID means it is a top level category, otherwise it corresponds to another category which is it's parent... is there a better way to structure the data and/or code this? the code is below, and it is just to display a category tree, but it results in many redundant queries... i don't want to run 50+ queries every time i want to display the tree...

 

$top_res = mysql_query("select CategoryID, CategoryName from tblCategory_test where ParentID = 0");

while($r = mysql_fetch_array($top_res))
{
    echo $r['CategoryName'].'<br />';
    $sub_res = mysql_query("select * from tblCategory_test where ParentID = $r[CategoryID]");
    while($sr = mysql_fetch_array($sub_res))
    {
        echo '|'.$sr['CategoryName'].'<br />';
        $ssub_res = mysql_query("select * from tblCategory_test where ParentID = $sr[CategoryID]");
        while($ssr = mysql_fetch_array($ssub_res))
        {
            echo '||'.$ssr['CategoryName'].'<br />';
            $sssub_res = mysql_query("select * from tblCategory_test where ParentID = $ssr[CategoryID]");
            while($sssr = mysql_fetch_array($sssub_res))
            {
                echo '|||'.$sssr['CategoryName'].'<br />';
                $ssssub_res = mysql_query("select * from tblCategory_test where ParentID = $sssr[CategoryID]");
                while($ssssr = mysql_fetch_array($ssssub_res))
                {
                    echo '||||'.$ssssr['CategoryName'].'<br />';
                }
            }
        }
    }
}

this works, but what if there is a category 10 levels deep? do i have to have nested loops to support that level?

thanks for any help...

Link to comment
https://forums.phpfreaks.com/topic/176851-solved-displaying-product-categories/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.