This post will explain how to show categories and sub-categories in a tree format in a directory.
Example:
We need to create a table called `categories` and the table Fields:
" id ", this should be a int(11), primary, and auto-increment.
" name ", this should be varchar(255) [ Name of the category ]
" parentid ", this should be int(11), [ " id " of the Parent category, if this is a sub-category, If " parentid " is 0, that means the category is a top-level category ]
Code for display Categories Dropdown:
$connection = mysql_connect('localhost', 'root', '');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db ('test1', $connection);
$sql = "SELECT * from categories order by name ASC";
$cats = mysql_query($sql) or die("Could not select category");
echo "<select name="category">";
recall (0,0,$cats);
echo "</select><br>";
Function recall() is the actual function that is going to generate the tree structure for our categories and sub-categories. We initially pass it values of 0,0,and $cats for its root, depth, and the actual query data. We pass is 0 and 0 for root and depth because initially we want to start from top level directories.