N-Level Category.

Standard

Hello i am back with one new post for N-Level Category listing just like magento.

In this lesson we will create a N-Level Category listing so please follow along with me.

First of all we need to have one table named master_maincat and its fields are as below.

1. ID -> AutoIncreament,Priamry Key

2. catname -> varchar(200)

3. parent_id -> int(11) Most important filed in this table.

Now here is the code is coming.

This code has only one function which is recursive.

It means that function call it self inside of it.

Here is Code :

function get_cat_selectlist($current_cat_id, $count)
{
    static $option_results;
    // if there is no current category id set, start off at the top level (zero)
    if (!isset($current_cat_id))
    {
        $current_cat_id =0;
    }
    // increment the counter by 1
    $count = $count+1;
    $sql =  'SELECT id, catname from master_maincat where parent_id =  
            '.$current_cat_id .' order by catname asc ';
    $get_options = mysql_query($sql)or die(mysql_error());
    $num_options = mysql_num_rows($get_options);
    if ($num_options > 0)
    {
        while (list($cat_id, $cat_name) = mysql_fetch_row($get_options))
        {

            if ($current_cat_id!=0)
            {
                $indent_flag =  '--';
                for($x=2; $x<=$count; $x++)
                {
                    $indent_flag .=  ' >';
                }
            }
        $cat_name = $indent_flag.$cat_name;
        $option_results[$cat_id] = $cat_name;
        get_cat_selectlist($cat_id, $count );
        }
    }
    return $option_results;
}

Now in last just add below code.

<?php
     echo '<select name="catid" id="catid">';
     echo '<option value="0">-- Select -- </option>';
     $get_options = get_cat_selectlist(0, 0);
     echo count($get_options);
     if (count($get_options) > 0)
     {
          $categories = $_POST['id'];
          foreach ($get_options as $key => $value) 
          {
              $options .="<option value=\"$key\"";
              $options .=">$value</option>\n";
          }
     }
     echo $options;
     echo '</select>';
?>

Above code will create drop down with the category listing.
It will show child category underneath the parent category just like magento code.
Chrees….Enjoy..
Feel Free to add comment….

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s