in reply to Selecting DB

Note: Pseudo-Code in this answer is written from memory and is untested. Didn't have time to build it to scale or to paint it.

Why code the stuff twice? you can put the database stuff into a function and return the result. Then run a foreach loop to request everything:

my @userids = ('XD4555', 'JJKKKK'); my @mails; foreach my $userid (@userids) { push @mails, getMails($dbh, $userid); } sub getMails { my ($dbh, $userid) = @_; my $sth = $dbh->prepare("SELECT snd.EMAIL FROM FUSERS as m JOIN USERS as snd ON snd.USERID = m.USERI +D WHERE m.USERID_IM = ?"); $sth->execute($userid); my $mails = $sth->fetchall_arrayref(); return @{$mails}; # Caller wants an array, so deref }

Of course, with most databases you can use the IN keywords to look for multiple matches at once. This is generally faster, since you have less calls to the database AND the statement optimizer only has to run once:

my @userids = ('XD4555', 'JJKKKK'); my $sth = $dbh->prepare("SELECT snd.EMAIL FROM FUSERS as m JOIN USERS as snd ON snd.USERID = m.USERID WHERE m.USERID_IM IN (?)"); $sth->execute(\@userids); my $mails = $sth->fetchall_arrayref();

It's also important here that you completely fail to error-check the database calls. This will lead to all sorts of problems and wrong results. And SELECT statements usually require a call to finish(). Try something like this:

use strict; use warnings; use Carp; ... my $dbh = DBI->connect(...parameters here...) or croak("$!"); ... my $sth = $dbh->prepare(...statement here...) or croak($dbh->errstr); $sth->execute(...args here...) or croak($dbh->errstr); my $mails = $query->fetchall_arrayref(); $sth->finish;

Also, it would be a VERY good idea to use proper transactions (not that autocommit BS), especially if you also INSERT/UPDATE/DELETE.

if($dbh->do(...somestuff...) && $dbh->do(...otherstuff...)) { $dbh->commit; } else { print STDERR "Database error: ", $dbh->errstr, "\n"; $dbh->rollback; }

PerlMonks XP is useless? Not anymore: XPD - Do more with your PerlMonks XP