don't see the issue yet, but here's a crack at refactoring to simplify it some, which hopefully will lead you in the right direction..
recurQuery(0,0);
my $cat_sth = $dbh->prepare("SELECT id, parentid, catname from categor
+ies WHERE parentid = ?");
sub recurQuery {
my ($parentId, $level) = @_;
$cat_sth->execute($parentId) or die $dbh->errstr;
while (my $data = $cat_sth->fetchrow_hashref) {
printf qq{ <option name="%s">%s%s</option>\n },
$data->{catname},
' *' x $level,
$data->{catname},
;
recurQuery( $data->{id}, $level+1 );
}
}
Some notes:
- prepare the statement once
- use placeholders
- the query only needs to be in the function once -- recursion does the rest; don't need to pre-test for rows .. the while loop just won't happen in the next level if there aren't any more children
- the x operator can replace the for loop for the indenting
- printf for cleaner output (also consider separating logic/presentation even further by having the recurQuery return an array, and loop over that to display later)
- fetch hashref's instead of rows -- much easier to read a key name than just an array index
You should put in some protection for infinite recursion, too.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.