Updating lots of database fields in a single row

Philip Skinner me at philip-skinner.co.uk
Tue Jan 22 23:47:13 GMT 2013


Maybe something like:

my $qry = $self->dbh->prepare("UPDATE table SET " . join (sort(@fields), 
'=?, ') . " WHERE id=?");
my $affected = $qry->execute(@hash{sort(keys %hash)}, $id);

Though I've had quite a bit to drink.

On 01/22/2013 10:57 PM, Andrew Beverley wrote:
> 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 = ?");
> $sth->execute($opdefs_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.
>
> Thanks,
>
> Andy
>
>



More information about the london.pm mailing list