Reputation: 233
How to filter query parameters before inserting them into table to prevent sql injection?
Have such code:
$QueryParams = Yii::$app->request->getQueryParams();
$model = new Accounts();
$model->attributes = $QueryParams;
$connection->createCommand()->insert('accounts', $model->attributes)->execute();
Is this safe approach?
Upvotes: 4
Views: 7624
Reputation: 16276
The approach is safe. But, if the Accounts
class is an ActiveRecord
class (extends it), then you can simplify your code:
$model->load(Yii::$app->request->get());
$model->save();
It's equivalent to:
$connection->createCommand()->insert('accounts', $model->attributes)->execute();
Which is less intuitive, and may even have compatibility problems if you are using a different kind of database.
Also, sometimes you need raw queries. In this case it's preferred to use prepared statements:
$result = $connection
->createCommand('SELECT id FROM accounts WHERE name=:name')
->bindValues([':name' => $name])
->queryColumn();
There is a good Yii2 security best practices guide on GitHub.
Upvotes: 2
Reputation: 566
The approach is safe, but there is a better one:
$model = new Accounts();
if ($model->load(Yii::$app->request->get()) && $model->save()) {
// 'when the model is saved' logic here
}
// other code
This basically does, what the posted code does, but includes model validation, is shorter, and is easier to understand.
Upvotes: 4