Creating endless subcategory levels?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Creating endless subcategory levels?

Post by Sindarin »

So I am creating a menu with categories and subcategories. The problem is that there might be sub-subcategories or even sub-sub-subcategories in the future. How can I make it so the subcategory levels of a category can be endless?

I am using the following approach, the subcategories are parented to each category's index number:

Code: Select all

<?php
 
//connect to DB
require_once('database-connect.php');
 
$cat_query = "SELECT * FROM categories ORDER BY category_index ASC"; 
$cat_result = mysql_query($cat_query) or die('Error in Query: ' . mysql_error());
 
//create a combobox
echo '<select name="select" id="select">';
 
while($row = mysql_fetch_array($cat_result)){
 
$category_index=$row['category_index'];
$category_title=$row['category_title'];
echo '<option value="'.$category_index.'">'.$category_title.'</option>';
        
        
//SUBCATEGORIES
$subcat_query = "SELECT * FROM subcategories WHERE subcategory_parent='$category_index' ORDER BY subcategory_index ASC"; 
$subcat_result = mysql_query($subcat_query) or die('Error in Query: ' . mysql_error());
        while($row = mysql_fetch_array($subcat_result))
        {
        
        $subcategory_index=$row['subcategory_index'];
        $subcategory_title=$row['subcategory_title'];
        echo '<option value="'.$subcategory_index.'">--'.$subcategory_title.'</option>';        
        
        }
//END OF SUBCATEGORIES
        
}
 
echo '</select>';
 
mysql_close();
 
?>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Creating endless subcategory levels?

Post by requinix »

How to do it in the database? Each thing keeps track of its parent (or 0, or 1, or some special, unused number for the top-most thing).

How in PHP? Depends what you're trying to do (specifically, how you show that something is a child - indentation, numbering, etc). 99% of people use recursion: easy, but much less efficient than what the other 1% of people discovered they could do.
Post Reply