Hi. I’m quite new at Yii and I looked at a lot of forum topics here and read the documentation, but I couldn’t find a clear answer about the prevention of SQL injection when using Active Record.
OK, but what is the difference if I use findByAttributes or findAllByAttributes like I did in my example above and if I bind the parameters like columnNameInDb = :someVarName? In my example there is less code and is more readable. That’s what is confusing to me, I thought maybe my example is prone to SQL Injection.
I agree with you that the documentation is a little too short on SQL injection prevention.
The most basic methods are CActiveRecord::find() and CActiveRecord::findAll(), where you can specify a raw SQL clause for $condition parameter like this:
In all other CActiveRecord::findXXX() methods, Yii will try to use the 2nd syntax internally.
So you are safe as long as you use those methods in the way they are expected to be used.
But you can still use a raw SQL clause as $condition parameter for those methods. You have to use $params parameter whenever it is necessary.
The 2nd one will go through the model validation, while the 1st one will not … that’s right.
But the both of them are equally safe in the SQL context, because the attributes (e.g. ‘name’) will be properly escaped before saving. Note that the attributes are not safe as they are. They can contain a dangerous SQL string even after they passed the model attribute validation.
I don’t care for model validation in this case, since the ‘name’ parameter can be any string with any length, so it can contain dangerous SQL string in it. But both of them are safe from SQL injection, no matter if I use it like $model->attributes = $_POST[‘User’]; or if use it like $model->name = $_POST[name];?
I like Yii a lot, but I think some of the things regarding security (sql injection, xss…) are not well documented or are a little confusing.