Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Escaping %params

by FloydATC (Deacon)
on Jan 21, 2014 at 16:44 UTC ( #1071494=note: print w/replies, xml ) Need Help??

in reply to Escaping %params

Every minute spent quoting variables by hand and working around the endless stream of problems it will inevitably lead to, is a complete waste.

Just rewrite the queries to use placeholders, because sooner or later that's what you will end up having to do. Not only does it solve all problems related to SQL injection and special characters, it also makes your code easier to read and maintain. With most databases it will even improve performance.

And no, it's not difficult either. Just replace this

my $sth = $dbh->prepare(" SELECT * FROM foo WHERE bar=$qstring1 AND baz=$qstring2 "); $sth->execute();

with this

my $sth = $dbh->prepare(" SELECT * FROM foo WHERE bar=? AND baz=? "); $sth->execute($string1, $string2);'s really that simple!

Now, if you really REALLY must quote each variable because you have to build the queries on the fly, don't do the quoting yourself using regular expressions. Instead, use the DBD "quote" method conveniently provided for you. The following code works for simple cases:

my %quoted = map { $_ => $dbh->quote($params{$_}) } keys %params;

It produces a copy of the original hash, with all values properly quoted for safe use by the database you happen to be working with.

-- FloydATC

Time flies when you don't know what you're doing

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1071494]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2018-01-22 07:00 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (232 votes). Check out past polls.