Blogroll

 

Enter your email address:

Delivered by FeedBurner

Search


« Get Ready for Water-Powered Cell Phones | Main | 3 New Experimental Views for Web Search »

Categories and subcategories in select list

By admin | January 26, 2008

I was searching for ready script for creating categories and sub categories in one select list but could not find solution for it. I am sharing this simple code snippet for all PHP developers because these type of ready functions help a lot in development and make coding easy. This is not a perfect solution but a good sample to start making select lists that shows categories and subcategories. Following is the table structure for ‘category’ table.

CREATE TABLE `category` (
`cat_id` mediumint(5) unsigned NOT NULL auto_increment,
`cat_name` varchar(100) default NULL,
`cat_parent` mediumint(5) default NULL,
PRIMARY KEY (`cat_id`)
)insert into `category`(`cat_id`,`cat_name`,`cat_parent`) values (1,’Cars’,0),(2,’Toyota’,1),(3,’Suzuki’,1),(4,’Trucks’,0),(5,’Blue Toyota’,2),(6,’Red Toyota’,2),(7,’Ford’,4),(8,’Red Suzuki’,3);

 

<?php
 $nav_query = mysql_query("SELECT * FROM `category` ORDER BY `cat_id`");
 $tree = "";
 $depth = 1;
 $top_level_on = 1;
 $exclude = array();
 array_push($exclude, 0);
 while ($nav_row = mysql_fetch_array($nav_query)){
 	$goOn = 1;
 	for($x = 0; $x < count($exclude); $x++ ){
 		if ($exclude[$x] == $nav_row['cat_id']){
 			$goOn = 0;
 			break;
		}
 	}
	if ( $goOn == 1 ){
		$tree .= '<option value="'.$nav_row['cat_id'];
		$tree .= '">'. $nav_row['cat_name'] . "</option>";
 		array_push($exclude, $nav_row['cat_id']);
  		if ( $nav_row['cat_id'] < 6 )
 		{ $top_level_on = $nav_row['cat_id']; }
		$tree .= build_child($nav_row['cat_id']);
 		}
 }

 function build_child($oldID){
    global $exclude, $depth;
    $child_query = mysql_query("SELECT * FROM `category` WHERE cat_parent=$oldID");
    while ($child = mysql_fetch_array($child_query)){
        if ($child['cat_id'] != $child['cat_parent']){
            $tempTree .= '<option value="' .$child['cat_id']. '">';
            for ( $c=0;$c<$depth;$c++ )
            { $tempTree .= " "; }
            $tempTree .= "---" . $child['cat_name'] . "</option>";
            $depth++;
            $tempTree .= build_child($child['cat_id']);
            $depth--;
            array_push($exclude, $child['cat_id']);
        }
    }
 return $tempTree;
}

echo '<select>';
echo $tree;
echo '</select><br>';

?>

Looking for better solution…

Popularity: 95% [?]

Bookmark this article! [?]

BlinkbitsBlinkListsBlogLinesBlogmarksBuddymarksCiteULikeCo.mmentsDel.icio.usDiggDiigo

FarkFeed Me LinksFurlGoogleLinkagogoma.gnoliaNetvouzNewsvinePropellerRawsugar

RedditRojoSimpySphinnSpurlSquidooStumbleUponTailrankTechnoratiYahoo

Topics: PHP |

2 Responses to “Categories and subcategories in select list”

  1. Saima Khan Says:
    January 26th, 2008 at 11:09 pm

    Well Dude. Nice share. I was also trying this. I have succeed to make some what is called hierarchical menu in select list just like this

    Home->Fruit->Orangre
    Home->Animal->Lion

    It has little problem. It requires that you supply categories or links in correct order otherwise it will not work. I am trying hard to fix but no success. Can you help me. Here is the code.

    <?php
    
    function getList($iCategoryID, $host_addr){
    	$list = "";
    
        	while ($iCategoryID > 0){
    			// This query can return one record only because the 'cat_id' field is a primary key
    			$sQuery = "SELECT cat_parent, cat_name
    						FROM category
        	    		    WHERE cat_id=$iCategoryID";
    
    			$resID = mysql_query($sQuery); // Execute query
    
    			if ($resID) {
    	            if (mysql_num_rows($resID) == 0)
                    	$iCategoryID = 0; // Show the root category
    				else{
    	                $resRow = mysql_fetch_assoc($resID); // Get category name and parent category ID
                        if (strlen($list) == 0) // We don't need link for the current category
    	                    $list =  $resRow['cat_name'] ;
                        else{ // Create links on the parent categories
    
    						$list = $resRow['cat_name'] . " > " . $list;
                        }
                        $iCategoryID = $resRow['cat_parent']; // One level up
    	            }
    	            mysql_free_result($resID); // Free memory associated with the $resID
    	        }
    	        else{ // Process errors
    	            echo "Error#: ". mysql_errno() . " Description: ” . mysql_error() . ““;
                    $iCategoryID = 0;
                }
            }
    	    // The root directory always the same
    	    $list = “Home  > ” . $list;
    
        return $list; // Return path to the specified category
    }
    $nav_query = mysql_query(”SELECT * FROM `category` ORDER BY `cat_id`”);
    echo ‘<select>’;
    while($row = mysql_fetch_array($nav_query)){
    	echo ‘<option>’;
    	echo getList($row[’cat_id’]);
    	echo ‘</option>’;
    }
    echo ‘</select>’;
    ?>
    
  2. Your Wish Says:
    January 30th, 2008 at 3:56 am

    I was searching net for adding categories and subcategories in select list. This is the only solution i have found. Is there any other source. Its not 100% accurate.

Comments


Comments links could be nofollow free.