I'm a little bit confused about the way DBI works when I re-use a prepared statement handle inside a while loop. Here's what I mean (table contains a set of tree structure data where elements refer to a parent_id):

my $prepared_handle = $dbh->prepare('SELECT * FROM table WHERE parent_ +id = ?'); : : : get_children(0); sub get_children { my $parent_id = shift; $executed_handle = $prepared_handle->execute($parent_id); while (my $pointer = $executed_handle->fetchrow_hashref) { $results .= $pointer->{id}."\n"; get_children($pointer->{parent_id}); } }

This sort of code doesn't seem to work because the nested call to get_children() appears to be overwriting the previous query. I'm getting:

Top level A Top level B Second Level A Second Level B

and then it stops, instead of continuing like so:

Top level A Top level B Second Level A Second Level B Top level C Top level D

Now this isn't a major problem, I can just re-prepare the $prepared_handle inside get_children() each time instead of using a globally prepared one, but this is less obviously efficient.

Is there an efficient way around this or is this just a limitation of the DBI interface?

(This is on mysql if it makes a difference)

Cheers
MattLG


In reply to 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.