Re: Recursive Select Box
| From: | Matt Palermo | Date: | Thu, 19 Feb 2004 04:03:09 +0000 |
| Subject: | Re: Recursive Select Box | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-178204@lists.php.net to get a copy of this message | ||
No, i'm using a MySQL DB.
"Justin Patrin" <papercrane@reversefold.com> wrote in message
news:20040218220602.22224.qmail@pb1.pair.com...
> Matt Palermo wrote:
>
> > Hey everyone. I'm looking for assistance/suggestions/answers on how to
> > build a select dropdown box from data that needs to be pulled
recursively
> > from a MySQL database. Basically the situation is mainly for a
dicussion
> > thread system type of thing where I have categories nested inside
> > categories, nested inside categories... Anyway, I want to be able to
build
> > a drop down box containing all the categories indented underneath it's
> > parent category to look something similar to this:
> >
> > -------------------------
> > Top Level Category
> > - Nested Category
> > - Lower level
> > - Etc....
> > Top Level Category
> > - Nested Category
> > Top Level Category
> > -------------------------
> >
> > Then the user will be able to select one from the dropdown menu. I have
all
> > the categories stored in a MySQL database called site_categories. The
table
> > is setup like this:
> >
> > __________________________________
> > | Cat_ID | Cat_Parent | Cat_Name |
> > |---------------------------------------------|
> > | 1 | 0 | Top Level 1 |
> > |---------------------------------------------|
> > | 2 | 1 | Nested 1 |
> > |---------------------------------------------|
> > | 3 | 0 | Top Level 2 |
> > |---------------------------------------------|
> > | 4 | 2 | Nested 2 |
> > |---------------------------------------------|
> >
> > Sorry for the bad pictures you hopefully you get the idea. Anything
with a
> > 0 Cat_Parent is a Top Level category. Then the others are all nested
inside
> > other categories that have the same Cat_ID as the nested categories
> > Cat_Parent. I basically need help creating a properly indented dropdown
> > menu box using this structure from the database. I assume I'm gonna
have to
> > use some sort of recursion here, but I'm not sure how to go about this.
> > Please help if you can.
> >
> > Thanks,
> >
> > Matt
> > http://sweetphp.com
>
> I'd suggest using a recursive function. (I'm assuming you're using PEAR
> DB...)
>
> function getSelect(&$db, $catParent = 0, $indent = '') {
> $sth = $db->query('SELECT * FROM categories WHERE Cat_Parent =
> '.$catParent);
> while($rec = $sth->fetchRow()) {
> echo '<option
>
> value="'.$rec['Cat_ID'].'">'.$indent.$rec['Cat_Name'].'</option>';
> getSelect($db, $rec['Cat_ID'], $indent.' ');
> }
> }
>
> $db = DB::connect('mysql://user:pass@host/db');
> $db->setFetchMode(DB_FETCHMODE_ASSOC);
> echo '<select name="selectBox">';
> getSelect($db);
> echo '</select>';
>
> I think that will work ;-)
>
>
> --
> paperCrane <Justin Patrin>