Forum Moderators: coopster & phranque

Message Too Old, No Replies

escaping single quotes within a string

escaping single quotes within a string

         

scotty28

7:21 pm on Jul 2, 2003 (gmt 0)

10+ Year Member



I am trying to insert a text string into a MySQL database, I am reading the information from a flatfile and sending it to a database.

I am getting an error whenever the text string contains a single quote. Is there any module in PERL to handle this... or do you think i should just check for the single quote within each string and replace it with \'

thanks,
Scott

sugarkane

8:18 pm on Jul 2, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld Scott

Yep, the DBI module can handle this for you, using the 'quote' function. EG:

[perl]
$dbh=DBI->connect('DBI:mysql:my_db:my_host', 'username', 'password');
$string=$dbh->quote("$string");
my $squery='INSERT into my_table (column) values ($string)';
my $sql=$dbh->prepare($squery);
$sql->execute;
$dbh->disconnect;
[/perl]

It's important to note that the quote() function will add the necessary quote marks to the string as well as escaping any special characters in there, so you don't need to include any quote marks in your SQL query.

scotty28

12:45 am on Jul 3, 2003 (gmt 0)

10+ Year Member



Thanks for the tip sugarkane.