LoginSignup
1
1

More than 5 years have passed since last update.

Perl_配列を利用してSQL実行するとき、SQLインジェクションを防ぐ方法

Posted at

要件
・外部から取得したリストの値を利用してDB更新したい。
・取得するリストで、要素数が毎回変わる。
・SQLインジェクションのリスクを避けたい。 :spy_tone5:

コード例


#ステータス更新の関数を呼ぶ

&updateStatus($dbh, @list);


sub updateStatus{

   #関数を呼ぶとき渡すパラメター。 $dbh:DB接続の設定、@list:取得のリスト配列
   my($dbh, @list)=@_;

   #配列の要素数を取得
    my $cnt=@list;


   #要素数と同じ数の"?マーク"文字列を作って、SQLを実行する

    my @mark;

    for(my $i=1; $i<=$cnt; $i++){
        push(@mark, "?");
    }

    my $markString=join(',',@mark);


    my $sql1=qq[
              UPDATE table1
              SET status = '1'
              WHERE id in ($markString)
        ];

    my $sth = $dbh->prepare($sql1)|| die "$DBI::errstr";


   #各要素数のbind_paramを作る

    for(my $j=0; $j<$cnt; $j++){
        my $k=$j+1;
        $sth->bind_param($k, $list[$j]);
    }

    $sth->execute || die "$DBI::errstr";

   //AutoCommit がオフ(0)の時
    $dbh->commit;

}
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1