use strict; use warnings; use DBI; use Data::Dumper; use CGI::Pretty qw(:standard *ul); my %node; my $dbh = DBI->connect( qw(DBI:vendor:database:host user pass), {RaiseError=>1} ); print header(),start_html('messages'), h1('messages'),start_form, 'New thread title: ', textfield('name'),br, 'Parent thread: ', textfield('parent'),br, submit('go'),end_form, ; insert_message(param('name'),param('parent')) if param('go'); display_messages(); print end_html; $dbh->disconnect; sub display_messages { my $sth = $dbh->prepare('select id,name,parent from node'); $sth->execute; while (my $row = $sth->fetchrow_hashref()) { $node{$row->{id}} = { name => $row->{name} }; push @{$node{$row->{parent}}->{children}}, $row->{id} if $row->{parent}; } # uncomment this to see the datastructure #print pre(Dumper \%node),hr; print start_ul; display_thread($_) for sort {$a<=>$b} keys %node; print end_ul; } sub display_thread { my $id = shift; my $node = delete $node{$id}; return unless $node; print li("$id: " . $node->{name}); return unless $node->{children}; print start_ul; display_thread($_) for @{$node->{children}}; print end_ul; } sub insert_message { my ($name,$parent) = @_; my $sth = $dbh->prepare(' insert into node(name,parent) values(?,?) '); $sth->execute($name,$parent); } # this sub is not used, but i'll leave it anyway ;) sub get_last_id { return $dbh->selectcol_arrayref('SELECT last_insert_id()')->[0]; }