Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

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);'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?

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2015-12-01 06:39 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (795 votes), past polls