Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
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}, '&nbsp;*' 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.

In reply to Re: Possible loop problems in database query by davidrw
in thread Possible loop problems in database query by coldfingertips

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2022-05-25 13:02 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (90 votes). Check out past polls.