Perl and parameterised statements

Viewed 94

i'm looking for confirmation that parameterised statements are not being executed correctly. Current code is as follows:

$ywant = "user supplied integer";
$select = "SELECT a.Authors, a.PublicationYear, a.Title, a.URL, a.ArticleID, f.Format ".
          "FROM   tbl_ETI_Article a, tbl_ETI_Format f  ".
          "WHERE  a.PublicationYear = '".$ywant."' ".
          "AND a.FID = f.FID ".
          "ORDER BY a.PublicationYear DESC, a.Title ASC";

$sth = $dbh->prepare( " $select " );
$sth->execute();

i understand that the $ywant variable in the select string should be replaced with a placeholder '?' and then the user supplied data be placed as an argument in the execute statement.

My question is does the above still offer any protection against injection attacks as it is still "being prepared"?

2 Answers

That is a risky SQL, because of $ywant may have malicious code if you can't trust its source. So it is much better to do this:

$ywant = "user supplied integer";
$select = qq{SELECT a.Authors, a.PublicationYear, a.Title, a.URL, a.ArticleID, f.Format
FROM   tbl_ETI_Article a, tbl_ETI_Format f
WHERE  a.PublicationYear = ?
AND a.FID = f.FID
ORDER BY a.PublicationYear DESC, a.Title ASC};

$sth = $dbh->prepare($select);
$sth->execute($ywant);

And avoid any SQL Injection potential problem. The prepare statement doesn't protect you by itself for this kind of attack

My question is does the above still offer any protection against injection attacks as it is still "being prepared"?

No.

Using parameters protects against SQL injection. Prepared statements do not (except insofar as they enable the use of parameters) .

Related