Jump to content

Categories / mySQL


atholon

Recommended Posts

Hi there,

 

So I made this table called categories for my site:

categoryid int(11)

title varchar(255)

description varchar(255)

parentid int(11)

 

I want to loop through the categories and display a list of everything...in a hierarchy like this:

MainCategory

- SubCat

---SubCatOfSubCat

-----SubCatofSubCat

AnotherMainCat

- SubCat

----SubCatofSubcat

etc...

 

The goal is to to have limitless categories for the website.

 

How should I go about doing this? My friend told me to use a class but I am not sure how to go about it. Could someone help?

Link to comment
https://forums.phpfreaks.com/topic/107014-categories-mysql/
Share on other sites

You need a recursive function

<?php

function listSubcats ($parent, $level=0)
{
$sql = "SELECT categoryid, title FROM categories WHERE parentid = $parent";
$res = mysql_query($sql);
while (list($id, $title) = mysql_fetch_row($res))
{
	$indent = str_repeat('---', $level);
	echo "$indent $title<br/>";
	listSubcats ($id, $level+1);                       // list its subcats
}
}

listSubcats (0) ;                                          // call for top level
?>

Link to comment
https://forums.phpfreaks.com/topic/107014-categories-mysql/#findComment-548611
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.