Display nested categories inside Select Box , List ( UL, LI ) and BreadCrumb using single PHP Class

Creating categories and its sub categories is always prevalent when we are developing simple to huge applications. Basically we  will have the requirement of creating one- leveled subcategory of parent category but when we come across creating multi-leveled subcategories , then it  seems little vague, complex to meet the requirement. Here I have made a simple php class to create multi-leveled nested categories on select box, List and creating ‘BreadCrumb’ when navigated to those categories. Prime essence of this PHP class is use of recursive function ( calling parent function again and again ).

DEMO         SOURCE CODE

First lets create mysql table and insert data  inside it.

CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`parentId` int(11) NOT NULL,
PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Here I have created the table ‘categories’ with ‘id’ as primary key and ‘autoincrement’ set as true, ‘name ‘ as varchar  and ‘parentId’  where reference  id of its parent category is stored.

Note: If the category is  parent (.i.e which has no parent category)  then set its ‘ parentId’ as 0

Lets insert the data into above table.

INSERT  INTO `categories`(`id`,`name`,`parentId`) VALUES (1,'category1',0),(2,'category2',0),(3,'category3',0),(4,'category4',0),(5,'category1.1',1),(6,'category1.2',1),(7,'category1.1.1',5),(8,'category1.1.2',5),(9,'category1.13',5),(10,'category2.1',2),(11,'category2.2',2),(12,'category1.1.2.1',8);
Wake up PHP ,  now its your turn…….

PHP  Class for Database Connection:

class Database 
{ 
	var $username	=	"root";
	var $password	=	"";
	var $database	=	"multiplecategories";
	var $host 		= 	"localhost"; 
	var $mysqli;  
	function database_connect()
	{ 
		// connect to the database
                (object)$this->mysqli =  new Mysqli( $this->host, $this->username, $this->password, $this->database ); 
		if ($this->mysqli->connect_error) 
		  die("Connection Error : " . $this->mysqli->error);
		 return $this->mysqli;  
 
	} 
}

In the above class I have used ‘MysqlI‘ ( Mysql Improved Extension ) for mysql operations. Mysqli is also  one of the PHP API offering for  using mysql. The mysqli extension is included with PHP versions 5 and later.

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

Note:If mysqli is confusing and not used before then you can also use relevant mysql functions instead.
PHP Class : Nested Categories.

<?
/* Author Prabeen Giri <http://prabeengiri.com.np> <prabeen.giri@gmail.com> */		
class NestedCategories extends Database
{ 
 
	var $tableName ; 
	var $linkHref  ;
	var $_mysqli   ;  
        // constructor to set the value to the member variables
	function NestedCategories( $tableName , $linkHref = NULL ) 
	{ 
		$this->tableName 		= 	$tableName  ; 
 
                if (isset($linkHref))
		$this->linkHref			= 	$linkHref	; 
 
                (object)$this->_mysqli	        = 	$this->database_connect(); 
 
	} 
 
        //creates the nested drop down ..................... 
	public  function createNestedDropDown( $selectedId = NULL  , $parentId=0 , $counter = 0  )
	{ 
		if ($counter == 0 )
		{ 
			 echo "<select name='parentId'>";  
			 echo "<option value='0'>Parent</option>";  
		} 
 
		$sql = "select * from {$this->tableName} where parentId='{$parentId}'";
		echo $sql; 
		$result = $this->_mysqli->query( $sql ) or die( $this->_mysqli->error );
		// fetch all the result 
		while($row = $result->fetch_object()) 
		{ 
				// if only selectedId parameter is provided.
                        if(isset($selectedId))			  
		        $sel = $row->id == $selectedId ? 'selected="selected"':''; 
			echo "<option value='{$row->id}' {$sel}>". $this->timer($counter).$row->name . "</option>"; 
			// calling same function , recusrion 
			$this->createNestedDropDown($selectedId, $row->id , $counter+1) ; 
		} 
		if ($counter == 0 )
			echo "</select>" ; 	
	} 
	// to create the space on the drop down menu as the depth of the categories increases.
	private function timer( $counter  ) 
	{ 
		$space = ''; 
		for ($i = 0;$i < $counter ; $i++ ) 
			$space .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";  
		return $space; 
	} 
 
        // creates the nested list with ul , li , ul .................. can be use for the navigation and menus.
	public function createNestedList($parentId=0 , $counter = 0  )
	{ 
		if ($counter == 0 )
			 echo "<ul class='subMenu'>";  
 
		$sql = " select * from {$this->tableName} where parentId = {$parentId} ";
		$result = $this->_mysqli->query( $sql ) or die($this->_mysqli->error);
		while($row = $result->fetch_object()) 
		{ 
		        $res 	= 	$this->_mysqli->query ( " select * from {$this->tableName} where parentId = '" .$row->id . "'" ); 
			$tot 	= 	$res->num_rows;
			$href 	= 	$this->linkHref; 
			$ul 	=  	$tot == 0 ? "":'<ul>'; 
			$_ul 	= 	$tot == 0 ? "":'</ul>'; 
			echo "<li><a href='{$href}{$row->id}'>{$row->name}</a>"; 
			echo "{$ul}";  
			$this->createNestedList($row->id , $counter+1) ; 
			echo "{$_ul}"; 
			echo "</li>"; 
		} 
 
		if ($counter == 0 )
			echo "</ul>" ; 	
	} 
 
	//creates  breadCrumb as with all the parent categories. 
	public function breadCrumb ( $categoryId, $loop=0 ) 
	{ 
		$sql = " select * from {$this->tableName} where id = '{$categoryId}' ";
		$result = $this->_mysqli->query( $sql ) or die($this->_mysqli->error);
		$row 	= $result->fetch_object() ; 
		if( $loop > 0 )
		        $a     = "<a href='{$this->linkHref}{$row->id}'>{$row->name}</a>";
		else
			$a	= "<strong>{$row->name}</strong>";
		if ( $row->parentId != 0 ) 
			echo  $this->breadCrumb($row->parentId,$loop+1)."&nbsp;&raquo;&nbsp;".$a;
		else 
			echo   $a;
	} 
} 
?>

Invoke the Methods to render it in the browser.

 
	// first  parameter is  category table name  and second is the url on the anchor tag on list and breadcrumb
        $nc = new NestedCategories('categories','?categoryId=');
 
        //Nested Categories over Drop Down 
	// if you need some category on drop down to be selected like when we want to edit the information .
       // else omit the parameter .
        $nc->createNestedDropDown( 9 ); 
        or 
        $nc->createNestedDropDown( $_GET['categoryId'] ); 
        or 
        $nc->createNestedDropDown( ); 
 
        // Nested Categories over List 
	$nc->createNestedList(); 
 
        //Bread Crumb; 
	$nc->breadCrumb($_GET['categoryId']);

Note: If you are using createNestedList() method then script will automatically create the class as ‘subMenu’ on the first ul that it generates or top ‘ul’. You can use javascript or css to hide the inner list or make animations to create drop down menu , navigations

I hope this class will easily help you create the nested categories on drop down, list, and breadcrumb. If you have any problem in its usage then please free to respond me……….

DEMO         SOURCE CODE

1,984 views
Mysql, Php

Comments

8 Responses to “Display nested categories inside Select Box , List ( UL, LI ) and BreadCrumb using single PHP Class”

Leave Comment

(required)

(required)