For this type of scenario, I usually store individual
column names and values in a pair of arrays and join them,
something like this
if(is_valid($form{'field1'})){
push(@fields, 'field1');
push(@values, $form{'field1'});
}
if(is_valid($form{'field2'})){
push(@fields, 'field2');
push(@values, $form{'field2'});
}
# repeat, with appropriate validity tests, for
# each field/column
$query = $dbh->prepare("insert into table (" .
join(',',@fields) .
") values (" .
join(',', @values) .
")");
$query->execute;