Updating lots of database fields in a single row

Andrew Beverley andy at andybev.com
Tue Jan 22 22:57:29 GMT 2013

I've not been developing with Perl for long, so I'd like to know if
there is a better way of writing the following database query (or is
there a better place to ask?):

my @fields = qw(field1 field2 field3 field4 field5 field6 field7 ... );
my @updates;
foreach my $field (@fields)
    push @updates, "$field = '$hash->{$field}'" if $hash->{$field};
my $values = join ',', @updates;
my $sth = $self->dbh->prepare("UPDATE table SET $values WHERE id = ?");

Basically, I'd like to update lots of fields in a single database row.
Obviously I could write out each updated field individually, but I
wondered whether the above is considered tidier, or whether there is a
better way altogether? The problem with the above code is that I'm not
using placeholders and bind values (which I assume is to be preferred)
so I'll also need to escape values as required.



More information about the london.pm mailing list