hi
i want to update some products via Product::updateAll, but i cant give my new values via parameter. i worry about security issues like sql injection etc etc
Product::updateAll(['title' => 'new title'], 'id IN ( 1,2,3)');
what should i do?
thanks in advance.
mdomba
(Maurizio Domba Cerin)
June 25, 2016, 11:55am
2
Have you tried the 3rd parameter?
updateAll doc
how? like this:
Product::updateAll(['title' => ':title'], 'id IN ( 1,2,3)', [':title' => 'new title']);
Finally I had to use following :
Yii::$app->db->createCommand
Bizley
(Bizley)
June 26, 2016, 7:32pm
6
This should work:
Product::updateAll(['title' => 'new title'], ['id' => [1, 2, 3]]);
or if you want to bound parameter:
Product::updateAll(['title' => ':newtitle'], ['id' => [1, 2, 3]], [':newtitle' => 'new title']);
thx, i will test it
btw how do i know if model->findOne(id) does care about sql injection or not? what about queries with IN(x,y,z) clauses?
thanks
Bizley:
This should work:
Product::updateAll(['title' => ':newtitle'], ['id' => [1, 2, 3]], [':newtitle' => 'new title']);
didnt work, actually parameters only work if they are use in where section.
softark
(Softark)
June 27, 2016, 10:48am
9
You can do it like the following:
$title = 'This is the new title';
Product::updateAll(
['title' => new yii\db\expression(':newtitle')],
['id' => [1, 2, 3]],
[':newtitle' => $title]
);
You have to say that ‘:newtilte’ is an expression, otherwise it will be treated as a string literal.
But, in order to avoid sql injection, you may simply do it like this:
$title = 'This is the new title';
Product::updateAll(
['title' => $title],
['id' => [1, 2, 3]]
);
Yii will automatically use the parameter-binding approach for ‘title’ and $title.
You can check the source code of yii\db\QueryBuilder\update()
$this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
$this->buildFrom($query->from, $params),
$this->buildJoin($query->join, $params),
$this->buildWhere($query->where, $params),
$this->buildGroupBy($query->groupBy),
$this->buildHaving($query->having, $params),
];
$sql = implode($this->separator, array_filter($clauses));
$sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
if (!empty($query->orderBy)) {
foreach ($query->orderBy as $expression) {
if ($expression instanceof ExpressionInterface) {
$this->buildExpression($expression, $params);
}
}
}
if (!empty($query->groupBy)) {
foreach ($query->groupBy as $expression) {
if ($expression instanceof ExpressionInterface) {