I'm working on a hierachal table where I have:
TABLE_STUFF
~~~~~~~~~~~~~~~~~~~~
ID (pk)
name
parent_ID
As part of the project, I'm implementing a nested set
update methodology so the table looks like:
TABLE_STUFF
~~~~~~~~~~~~~~~~~~~~
ID (pk)
name
parent_ID
lft
rght
depth
lineage
I won't go into the details of nested set over adjacency model except one is good for updates and one for queries.
My code to update the table when an entry is added or removed follows:
sub rebuild_tree
{
my $dbh = shift;
my $dir_ID = shift;
my $left = shift;
my $right = $left + 1;
my $sql = "select ID, name from DIRECTORIES where parent_ID = ?";
my $sth = $dbh->prepare($sql);
$sth->execute($dir_ID) || return $right + 1;
my $row;
while($row = $sth->fetchrow_arrayref)
{
#print STDERR "Processing: ", $row->[0], " with name: ", $row-
+>[1],"\n";
$right = rebuild_tree($dbh, $row->[0], $right);
}
my $sql2 = "update DIRECTORIES set lft = ?, rght = ? where ID = ?"
+;
my $sth2 = $dbh->prepare($sql2);
$sth2->execute($left, $right, $dir_ID);
return $right + 1;
}
This code does work but I want to save my prepares across all calls to the function. I have tried using vars, ie:
use vars qw($sth);
....
# And then in the function
$sth || = $dbh->prepare($sql);
But the function only goes so deep before I get the following error:
DBD::mysql::st fetchrow_arrayref failed: fetch() without execute()
I assume this is because I am iterating over a statement handler and not creating a new one in each new function? If so, how can I take advantage of my prepare?
Sorry if this is a lame question but recursion always stumps me ;).
Ta, SP