Create multi-level category using recursive function

php-multi-level-recursive

well, Creating multi-level category system with PHP in not just a simple undertaking.
Many Developer usage different approach to manage this specific. They may possibly create 3 tables for initial level, subsequent level as well as 3rd level category (parent, sub category as well as sub sub cateogry).

The best method to acquire multi-level category using
recursive function
.
With this, let us build a database table i.e category. as shown below
.

Now time to get our hand dirty. Open your favorite editor, create a new file ‘category.php’ where we will list all category.
Create a new file i.e ‘class.php’ .Inside this we will create class and method to handle recursive function
also create a file to connect and select your database .i.e ‘config.php’

 

php mysql video tutorial in Hindi language by UnitedWebSoft

If you searching a good Web Development Training center where you learn advance practical project based training ,visit us , You will become confident developing any project after our training completion .

 

php-multi-level-category-recursive

  
  class cat{
 	public $child_cat_cid;




	function cat_list($p_cid=0,$space=''){
 	$q="SELECT * FROM category WHERE p_cid='$p_cid'";
	$r=mysql_query($q) or die(mysql_error());
	
	$count=mysql_num_rows($r);
	
	if($p_cid==0){
		$space='';
	}else{
		$space .="    ";
	}
	if($count > 0){
		
		while($row=mysql_fetch_array($r)){
			echo "".$space.$row['name']."";
			
			$this->cat_list($row['cid'],$space);
		}
		
	}
	
 
 }
 
  
  

Now we have created our class .Time to use this. So below in category.php , we have created a object from class ‘cat’ then access the method ‘cat_list’ as shown below

  

 <?php 
  require 'includes/config.php'; 
  require 'includes/class.php'; 
  $cat=new cat(); 
  if(isset($_POST['submit'])){ 
  	$p_cid=$_POST['p_cid']; 
	$name=$_POST['name']; 
	mysql_query("INSERT INTO category (name,p_cid) VALUES('$name','$p_cid') ") or die(mysql_error()); 
 } 

?>


<form action="" method="post"><select name="p_cid">
<option value="0">Select Category</option><?php $cat->cat_list(); ?>
</select>
Category : <input name="name" type="text" /> <input name="submit" type="submit" value="Submit" /></form>

After , you can access category.php in your localhost like http://localhost/php/category.php
Add some category and sub category inside this by selecting category as parent.
It’s ready to use php multi-level category .Follow Next tutorial to show products according to category selected .