http://www.perlmonks.org?node_id=608325


in reply to Possible loop problems in database query

The intent of your recursive function is "find every immediate child of the specified parentId, print it as an option element, immediately followed by all of its children, etc." There are two issues with your code breaking this:
  1. Your method is handling two levels per invocation, instead of just one.
  2. The recursive call to your function is passing the current element's parentid, not the id. (Remember, "immediate child of the specified/current element.")
This should help:
# my super recurse the tree function, takes 2 options being parentid, +and current level sub recurQuery { my ($myParentId,$level) = @_; my $data = "SELECT id, parentid, catname from categories WHERE par +entid = ?"; my $sth = $dbh->prepare($data); $sth->execute($myParentId) or die $dbh->errstr; my $indent = '&nbsp;*' x $level; # loop through results while (my ($id,$parentid,$catname) = $sth->fetchrow_array()) { # print the beginning of the option box print"<option name='$catname'>$indent$catname</option>\n"; recurQuery( $id, $level + 1 ); } }
pg