Category List Box More Than Two Levels?

Hello everyone,

I am currently working on the script taken from www.phpwebcommerce.com I am only a beginner and have been using it in a little project for an online game just to help my mates be able to trade items and such.

I have managed to get almost everything sorted apart from one thing. The function which gets the categories for a drop down select box.

Basically the category table has a field for Parent ID and Category ID the code below creates a dropdown list populated however it only works two levels deep.

Is there anyway to modify the function so that it can support more levels? I have been racking my brain and searching the web but my coding knowledge and skills are just not up to scratch for the job.

Anyhelp is greatly appreciated.

[php]
/*
Generate combo box options containing the categories we have.
if $catId is set then that category is selected
*/
function buildCategoryOptions($catId = 0)
{
$sql = “SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id”;
$result = dbQuery($sql) or die('Cannot get Product. ’ . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
    list($id, $parentId, $name) = $row;
    
    if ($parentId == 0) {
        // we create a new array for each top level categories
        $categories[$id] = array('name' => $name, 'children' => array());
    } else {
        // the child categories are put int the parent category's array
        $categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);    
    }
}    

// build combo box options
$list = '';
foreach ($categories as $key => $value) {
    $name     = $value['name'];
    $children = $value['children'];
    
    $list .= "<optgroup label=\"$name\">"; 
    
    foreach ($children as $child) {
        $list .= "<option value=\"{$child['id']}\"";
        if ($child['id'] == $catId) {
            $list.= " selected";
        }
        
        $list .= ">{$child['name']}</option>\r\n";
    }
    
    $list .= "</optgroup>";
}

return $list;

}

[/php]

Just a little bump as I still havent been able to figure this out :’(

Hi there,
i got the same problem from www.phpwebcommerce.com, I try to add a new product the combo box doesn’t allow me to select the category. Have u able to figure this out ?
Thanks

Sponsor our Newsletter | Privacy Policy | Terms of Service