Jump to content

Help with Category List Function


ca99uk

Recommended Posts

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:

 

/*
    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;
}

 

Basically the problem is that it only creates a category list of two levels e.g.

 

Parent

 

    Child

 

and I wish to be able to have more sub categories e.g.

 

Parent

 

    Child

 

        Child

 

            Child

 

Is there anyway of adapting this code so it can do something like that? Many thanks for any help.

Link to comment
Share on other sites

Firstly appologies I think I posted my first post (this one) in the wrong bit  :o

 

In terms of the database structure the table for categories has id and parent id fields so this as my understanding should mean that you can assign any number of parent / child relationships.

 

Below is the code from the actual page that calls the function:

 


<?php
if (!defined('WEB_ROOT')) {
exit;
}


if (isset($_GET['catId']) && (int)$_GET['catId'] > 0) {
$catId = (int)$_GET['catId'];
$sql2 = " AND p.cat_id = $catId";
$queryString = "catId=$catId";
} else {
$catId = 0;
$sql2  = '';
$queryString = '';
}

// for paging
// how many rows to show per page
$rowsPerPage = 20;

$sql = "SELECT pd_id, c.cat_id, cat_name, pd_name, pd_thumbnail
        FROM tbl_product p, tbl_category c
	WHERE p.cat_id = c.cat_id $sql2
	ORDER BY pd_name";
$result     = dbQuery(getPagingQuery($sql, $rowsPerPage));
$pagingLink = getPagingLink($sql, $rowsPerPage, $queryString);

$categoryList = buildCategoryOptions($catId);

?> 
<p> </p>
<form action="processProduct.php?action=addProduct" method="post"  name="frmListProduct" id="frmListProduct">
<table width="100%" border="0" cellspacing="0" cellpadding="2" class="text">
  <tr>
   <td align="right">View products in : 
    <select name="cboCategory" class="box" id="cboCategory" onChange="viewProduct();">
     <option selected>All Category</option>
<?php echo $categoryList; ?>
   </select>
</td>
</tr>
</table>
<br>
<table width="100%" border="0" align="center" cellpadding="2" cellspacing="1" class="text">
  <tr align="center" id="listTableHeader"> 
   <td>Product Name</td>
   <td width="75">Thumbnail</td>
   <td width="75">Category</td>
   <td width="70">Modify</td>
   <td width="70">Delete</td>
  </tr>
  <?php
$parentId = 0;
if (dbNumRows($result) > 0) {
$i = 0;

while($row = dbFetchAssoc($result)) {
	extract($row);

	if ($pd_thumbnail) {
		$pd_thumbnail = WEB_ROOT . 'images/product/' . $pd_thumbnail ."_64.png";
	} else {
		$pd_thumbnail = WEB_ROOT . 'images/no-image-small.png';
	}	



	if ($i%2) {
		$class = 'row1';
	} else {
		$class = 'row2';
	}

	$i += 1;
?>
  <tr class="<?php echo $class; ?>"> 
   <td><a href="index.php?view=detail&productId=<?php echo $pd_id; ?>"><?php echo $pd_name; ?></a></td>
   <td width="75" align="center"><img src="<?php echo $pd_thumbnail; ?>"></td>
   <td width="75" align="center"><a href="?c=<?php echo $cat_id; ?>"><?php echo $cat_name; ?></a></td>
   <td width="70" align="center"><a href="javascript:modifyProduct(<?php echo $pd_id; ?>);">Modify</a></td>
   <td width="70" align="center"><a href="javascript:deleteProduct(<?php echo $pd_id; ?>, <?php echo $catId; ?>);">Delete</a></td>
  </tr>
  <?php
} // end while
?>
  <tr> 
   <td colspan="5" align="center">
   <?php 
echo $pagingLink;
   ?></td>
  </tr>
<?php	
} else {
?>
  <tr> 
   <td colspan="5" align="center">No Products Yet</td>
  </tr>
  <?php
}
?>
  <tr> 
   <td colspan="5"> </td>
  </tr>
  <tr> 
   <td colspan="5" align="right"><input name="btnAddProduct" type="button" id="btnAddProduct" value="Add Product" class="box" onClick="addProduct(<?php echo $catId; ?>)"></td>
  </tr>
</table>
<p> </p>
</form>

 

Link to comment
Share on other sites

Hi Everyone,

 

been looking and still cant figure it out if anyone has any ideas greatly appreciated  :)

 


/*
    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;
}

 

 

Link to comment
Share on other sites

Hi Everyone,

 

I dont know if this is possible or impossible .... is it worth trying to figure out how to adapt the function to do more than two category levels or is a total rewrite needed? I honestly thought it would be quite straight forward but obviously does not seem so.. any pointer would be great.

 

Thanks.

Link to comment
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.