how to prevent sql injection from this query?

2020-05-06 23:45发布

问题:

I am using Yii 1, I want to build the following query:

$a = Model::model()->findAllBySql(
              'SELECT * FROM table WHERE name like "%'.$_GET['name'].'%"'
              );

To prevent the sql injection I wrote it as follow:

 $a = Model::model()->findAllBySql(
                      'SELECT * FROM table WHERE name like "%:name%"',
                      array("name"=>$_GET['name'])
                      );

but it returned no data. Are there any errors in this query ?

回答1:

When the placeholder is quoted it is not a placeholder, it is the literal value. Try it this way:

$a = Model::model()->findAllBySql(
                      'SELECT * FROM table WHERE name like :name',
                      array(":name"=> '%' . $_GET['name'] . '%')
                      );

The driver currently auto-appends the colons but it might not in the future, it is best to have the name match the placeholder.