You're not just re-using the prepared statement, you're interrupting it in the middle of each use. The next execute() drops everything that was found and cached previously and loads up a fresh list ready to be fetched. There's only one prepare, so there's only one cache of results that can be fetched. The trick is to fetch all your results first before issuing the next execute.

sub get_children { my $parent_id = shift; $executed_handle = $prepared_handle->execute($parent_id); # first retrieve all the results my @results; while (my $pointer = $executed_handle->fetchrow_hashref) { push @results, $pointer->{parent_id}; } # now deal with the results foreach (@results) { $results .= $_."\n"; get_children($_); } }

I'll also note that since you appear to be fetching only a single column (parent_id), then you could also skip the whole execute/fetch loop and select the results directly into an array ref. But I suspect your example may have been trimmed down for the purpose of the question, so this may not apply.

my $parent_id = shift; # first retrieve all the results my $results_ref = $dbh->selectcol_arrayref( $prepared_handle, undef, $parent_id); # now deal with the results foreach (@$results_ref) { $results .= $_."\n"; get_children($_); }

In reply to Re: Nesting prepared DBI handles by ruzam
in thread Nesting prepared DBI handles by MattLG

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



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.