0

The problem I am having is that I have a user input a string... Could be anything less than 156 characters, and the DBI statement inserts the string perfectly if there are no apostrophes or quotation marks in the string.

This works fine-> I am working! This doesn't work-> I'm not working!

To insert I use the following code:

    $sth = $dbh->prepare("INSERT INTO table VALUES('$var1','$var2','$var3')");
    $sth->execute();

I know that Perl interpolates the strings different with ' ' and " " but my program throws a fit when I try that. I've also tried using a join to join that prepare statement together using " " marks. The variable that stores the 155 characters is $var3 if that matters, and all 3 are VARCHAR attributes. Any suggestions?

James Brown
  • 899
  • 2
  • 13
  • 22

1 Answers1

6

You need to escape your variables.

It is exactly this oversight that hackers exploit to perform SQL injection attacks: read the story of poor little Bobby Tables. Indeed, you really should avoid ever evaluating your variables for SQL, by parameterising your prepared statement:

$sth = $dbh->prepare('INSERT INTO table VALUES(?, ?, ?)');
$sth->execute($var1, $var2, $var3);
Community
  • 1
  • 1
eggyal
  • 113,121
  • 18
  • 188
  • 221