I like to use join and map in order to cut down on too much static code and to simplify building SQL statements to pass to DBI. Ideally, some sort of database abstraction should be used, but it is not always an option.
Below is an example block of code that handles a CGI form submission with an action of "Add" or "Update". The SQL is built according to the action and passed to a single prepare and execute.
Below is an example block of code that handles a CGI form submission with an action of "Add" or "Update". The SQL is built according to the action and passed to a single prepare and execute.
my $sql;
my @fields = qw(field1 field2 field3 field4 field5);
my @bind_values;
if ($input->{action} eq "Add") {
$sql =
"INSERT INTO datatable (" .
join(", ", @fields) .
") VALUES (" .
join(", ", map {"?"} @fields) .
")";
map {push @bind_values, $input->{$_} } @fields;
}
elsif ($input->{action} eq "Update") {
$sql =
"UPDATE datatable SET " .
join(", ", map {"$_ = ?"} @fields) .
" WHERE primarykey = ?";
map { push @bind_values, $input->{$_} } @fields;
push @bind_values, $input->{primarykey};
}
if (length $sql) {
my $sth = $dbh->prepare($sql);
$sth->execute(@bind_values);
}

Leave a comment