in reply to Receinving hash where expecting a string

Assuming you want to insert all values from the hash into your database, you could use the following code:

my @keys = sort keys %cols; my $keystring = join ', ', @keys; my $valstring = join ', ', ('?') x scalar @keys; my $statement = qq{ INSERT INTO service_metrics ($keystring) VALUES ($valuestring) }; my @values = map { $cols{$_} } @keys; my $sth = $dbh->prepare($statement); if (! $sth) { die(sprintf('[FATAL] Could not prepare statement: %s\n\n + ERRSTR: %s\n', $db->errstr())); } $sth->execute(@values); if (! $sth) { die(sprintf('[FATAL] Could not execute statement: %s\n\n + ERRSTR: %s\n', $db->errstr())); } $sth->finish; $db->disconnect();

This is a bit less code and, by using placeholders, guards you against SQL injection.

You can learn more about placeholders in the DBI documentation.

The sorting of the keys eliminates the need to add supply an order manually.

If you have possibly undefined values, change the first line to

my @keys = grep { defined $cols{$_} } sort keys %cols;

Replies are listed 'Best First'.
Re^2: Receinving hash where expecting a string
by Anonymous Monk on Aug 15, 2007 at 13:41 UTC
    Many thanks for these responses. Using the $cols($_) and CGI:Vars has got the data into the db correctly. However, I'll also try the other method suggested by moritz and play with that.