Woodman has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I recently encountered a problem with a little DB application i wrote, when I enter a single quote in a string it malforms my SQL query. I could replace all the single quotes in strings before I assemble the query, but i would prefer if i could do it in the routine that sends the querys to database, but my tries to get a regex, that replaces only the single quotes in the actual strings have not been successful and i could not find a solution on the net. So I hope i can find a solution here.

example string : UPDATE SET column = 'foo bar' bar foo' foo bar',\n

Any help is appreciated Woodman

Replies are listed 'Best First'.
Re: Escape single quotes in a SQL query
by arc_of_descent (Hermit) on Jun 09, 2009 at 13:44 UTC
Re: Escape single quotes in a SQL query
by jettero (Monsignor) on Jun 09, 2009 at 14:56 UTC
    There are two main ways to deal with this using DBI. The first is their quote function:
    # this works, but don't do it... The "correct" way is bind-vars $value = $dbh->quote("sneaky text with posessives' in it"); $sql = "u +pdate set column = $value";

    The coolest most modern way to do it is bind vars:

    # Do this every time: my $sth = $dbh->prepare("update table set column=?") or die $dbh->errs +tr; $sth->execute("sneaky text with posessives' in it") or die $dbh->er +rstr;

    If you use the bind-vars every single time, you'll very rarely have the kinds of horrible security problems that plague early php programs (sql injection).

    -Paul

Re: Escape single quotes in a SQL query
by JavaFan (Canon) on Jun 09, 2009 at 13:50 UTC
    1. Use place holders. See the DBI manual.
    2. Use the quote method in the DBI.
    3. $value =~ s/'/''/g;