Indeed, psini is correct—placeholders should be your new best friend. Not only will they solve your quoting woes, more importantly they will provide a secure method of writing to a database, preventing such things as injection attacks.
However, it might be good to see an example of how you can more concisely deal with a hash of data that you want to write to the database using DBI. This clever piece of code (that I borrowed from someone in the Monastery years ago) builds your query using the keys and values of your hash of data. Note the ? placeholders.
my $stmt = qq/INSERT INTO books ( / . join(',', keys %hash) . qq/) VALUES (/ . join(',', ('?') x keys %hash) . qq/)/; my $sth = $dbh->prepare($stmt); $sth->execute(values %hash);
Here's a simplified example (I use CGI::Application in my own work) of an entire subroutine I place in a common module
sub write_to_db { my $table = shift; #pass in table name my $hash = shift; #pass in hash ref to data my ($stmt, $sth); #subroutine to connect to db my $dbh = dbconnect(server =>'master', db => 'member'); my %hash = %{ $hash }; #deref data if ($query->param('update')) { #set a hidden value in html form if + updating $stmt = qq/UPDATE $table SET updated_on = NOW(), / . join(' = ?, +', keys %hash) . qq/ = ? WHERE id = ?/; $sth = $dbh->prepare($stmt); $sth->execute(values %hash, $query->param('id')); #set a hidden +value } else { my $stmt = qq/INSERT INTO $table (created_on, / . join(',', keys + %hash) . qq/) VALUES (NOW(),/ . join(',', ('?') x keys %hash) . qq +/)/; my $sth = $dbh->prepare($stmt); $sth->execute(values %hash); } }
<shameless plug> you should take a look at this short tutorial for CGI::Application. CGI::App is a great habit to get into, and will simplify your life, or coding</shameless plug>
In reply to Re: Best way to deal with quotes in string with DBI
by bradcathey
in thread Best way to deal with quotes in string with DBI
by ewhitt
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |