Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.