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


in reply to Possible loop problems in database query

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: You should put in some protection for infinite recursion, too.