Dont know what to title this sorry!

  • Thread starter Thread starter Anonymous
  • Start date Start date
A

Anonymous

Guest
I have this code that pulls the categories and sub categories from a database.... how can i get it to indent sub categories...

thanks in advance

Code:
function build_menu ($category_id)
{
	db_connect();
	
	$query = mysql_query('SELECT * FROM `categories` WHERE `sub_category_of` =' . $category_id);
	while($row = mysql_fetch_array($query))
	{
		print($row['category_name'] . "<br>\r");
	}
	
	build_menu($row[category_id]);
}

I want it to look like

Code:
wheels 
  15" 
  16" 
  17" 

accessories 
  keyboard 
    wireless 
  mice
 
You could add a second, optional parameter to build_menu() that accepts a level-of-indentation argument:

Code:
<?php
function build_menu ($category_id, $indent = 0)
{
   db_connect();
   
   $query = mysql_query('SELECT * FROM `categories` WHERE `sub_category_of` =' . $category_id);
   while($row = mysql_fetch_array($query))
   {
      echo str_repeat(' &nbsp', $indent);
      ehco $row['category_name'] . "<br>\r";
   }
   
   build_menu($row[category_id], $indent + 1);
}
?>

In the above code I just used  , but in actuality I'd recommend strongly against it. Instead, I'd build an HTML list, wherein each sub-menu is a child list of a parent list-item. This way the indentation would not be handled by PHP at all, but instead by CSS. A List Apart has a good tutorial on list formatting called Taming Lists.
 
I'm in over my depth here but is there any way I could list just one sub category below what the user clicks...

ie user visits site without clicking anything

Code:
Wheels
Accessories

User Click "Accessories"

Code:
Wheels
Accessories
  Keyboard
  Mice

And so on?

Thanks in advance!
 
Yes, you'd just have to take whatever the user clicked on and do a query for that category.
 
but what happens if it is say 4 sub categories deep? and i want to leave the click sub categories open?
 
well if you are using proper HTML this should not be a problem. You are using lists to display the info right.

Code:
<ul>
     <li>wheels
          <ul>
               <li>15"</li>
               <li>16"</li>
               <li>17"</li>
           </ul>
     </li>
</ul>

<ul>
     <li>accessories
          <ul>
               <li>keyboard
                    <ul>
                         <li>wireless</li>
                    </ul>
               </li>
               <li>mice</li>
         </ul>
     </li>
</ul>

Then you can make it pretty with CSS
 
Back
Top