Html::encode() in Active Record and andFilterWhere()

Hi, I have a model and controller. Is it necessary to use Html::encode() in the Active Record class and for andFilterWhere() to avoid SQL injection

For Active Record as below

$countTalukas = Taluka::find()->where(['DistrictId' =>\yii\helpers\Html::encode( $id)])->count();

$talukas = Taluka::find()->where(['DistrictId' => \yii\helpers\Html::encode($id)])->all();

For andFilterWhere() in model search

 $query->andFilterWhere([
            'TalukaId' => \yii\helpers\Html::encode($this->TalukaId),
            'DistrictId' => \yii\helpers\Html::encode($this->DistrictId),
        ]);

No, you don’t have to do it. The query builder behind ActiveRecord will take care of it.

The only exception is when you want to use a raw string format.

1 Like

Ok, thanks for the reply

Html::encode() should not by used as a protection against SQL Injection - even if it works, it will generate invalid queries in some cases.

1 Like

Ah, yes, @rob006 is right.

Html::encode() is meant for escaping output.
The primary method against SQL Injection in Yii is the use of prepared statement.

Please check the following section of the Guide.

1 Like