# %yearly_page_hits defined elsewhere
my %new_monthly_page_hits;
# do this outside of the loop
my $dbh = DBI->connect("DBI:mysql:$sqlDatabaseName:","$mysqlUsername","$mysqlPassword")
or die "Connection Error: $DBI::errstr\n";
# loop through page keys
foreach my $page (keys %yearly_page_hits) {
# a single DBI call does it all
if (my @row = $dbh->selectrow_array(
"select count(page) from counter_monthly where page='$page'")) {
$new_monthly_page_hits{$page} = $row[0];
}
else {
$new_monthly_page_hits{$page} = 0;
}
print "$page $new_monthly_page_hits{$page}
";
}