Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Escaping %params

by FloydATC (Chaplain)
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);

...it'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


Comment on Re: Escaping %params
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1071494]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (10)
As of 2014-09-30 22:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (385 votes), past polls