use strict; # use em if use warnings; # you're not already my @loop; # first, prepare the SQL .. this can be more efficient. # BUT more importantly, this also is using placeholders # ALSO note the column aliases .. this makes things more convenient below. my $sth = $dbh->prepare("SELECT item1 as _first_item, item2 as _second_item, item3 as _third_item FROM table WHERE topic = ? ORDER BY id ASC"); # no need for a $y index .. foreach my $topic ( @topic[0 .. $x-1] ){ # just use an array slice to get the topics $sth->execute( $topic ); # passing a value to the placeholder push @loop, { _TOPIC => $topic, _ITEMS => $sth->fetchall_arrayref({}), # use a DBI function to get the AoH of items }; } $html->param(_TOPICS => \@loop); $html->output; #### my $sth = $dbh->prepare("SELECT item1 as _first_item, item2 as _second_item, item3 as _third_item FROM table WHERE topic = ? ORDER BY id ASC"); my @loop = map { $sth->execute( $_ ); { _TOPIC => $_, _ITEMS => $sth->fetchall_arrayref({}) }; } @topic[0 .. $x-1];