Recursive Function to output Category / Sub-category Breadcrumb

0 fetches the details of the category first $crumbsql = mysql_query("Select * From" data-image="" data-button="none"> Share
/// Recursive function to output the breadcrumb
function breadcrumb($id,$layer=0,$out=''){
/// If id = 0 outputs that it is Root Category. No need to go any further.
if($id ==0){
return "Root Category";
}
/// if id > 0 fetches the details of the category first
$crumbsql = mysql_query("Select * From category Where cat_id = '".$id."' ");
$crumbres = mysql_fetch_array($crumbsql);
/// for the first call (the category which will be displayed last) 
/// the layer is 0 to denote it is the current category and wont 
/// be having a link. 
if($layer == 0){
$out = $crumbres['cat_name'];
} else {
$out = ''.$crumbres['cat_name'].' > '.$out;
}
/// The layer increses to ensure all other categories have links.
$layer++;
/// If the parent category is greater than 0 the function is called again and the same steps are followed. 
/// If it reaches 0 then Root Category is printed and the output returned to process.
if($crumbres['cat_parent_id'] > 0){
$out = breadcrumb($crumbres['cat_parent_id'],$layer,$out);
} else {
$out = 'Root Category > '.$out;
}
return $out;
}

/// By default the category is set to 0.
$catid = 0;
/// Current category id is fetched from the URL Query String
if(isset($_GET['catid'])){
if($_GET['catid']!= ''){
$catid = $_GET['catid'];
}
}
/// Output of recursive function
echo breadcrumb($catid);

———————————————————————————-

The MySQL table used is below


CREATE TABLE `category` (
`cat_id` int(11) NOT NULL auto_increment,
`cat_name` varchar(255) NOT NULL,
`cat_parent_id` int(11) NOT NULL,
PRIMARY KEY  (`cat_id`)
)
This entry was posted in PHP, Recurssion and tagged , . Bookmark the permalink.
 

One Response to Recursive Function to output Category / Sub-category Breadcrumb

  1. Daniel says:

    Thanks this helped me out.

Leave a Reply

Your email address will not be published. Required fields are marked *

*