[英]Yii createCommand update part of string of multiple records
I'm using createCommand to replace part of a string in a field of multiple records. 我正在使用createCommand替换多个记录的字段中的一部分字符串。 The following code works well:
以下代码运行良好:
Yii::app()->db->createCommand("UPDATE table SET field=replace(field,'" . $old_string . "','" . $model->value . "') WHERE field LIKE '%" . $old_string . "%'")->execute();
(Yii 1.1) (Yii 1.1)
but, how can I parameterize it so that I can use :oldString & :newString, instead of linking the variables to the query directly? 但是,如何参数化它,以便可以使用:oldString&:newString,而不是将变量直接链接到查询?
Thanks. 谢谢。
You could use binding param 您可以使用绑定参数
$query = "UPDATE table
SET field=replace(field, :old_string , :new_string)
WHERE field LIKE concat('%', :old_string2, '%')";
$command = Yii::app()->db->createCommand($query);
$command->bindParam(":old_string", $old_string, PDO::PARAM_STR);
$command->bindParam(":new_string", $model->value, PDO::PARAM_STR);
$command->bindParam(":old_string2", $old_string, PDO::PARAM_STR);
$command->execute();
You just need to replace values with parameters placeholders in query and pass real values to execute()
. 您只需要在查询中用参数占位符替换值,然后将实际值传递给
execute()
。 The only tricky part is parameter for LIKE
, since %
needs to be inside of parameter value, not query: 唯一棘手的部分是
LIKE
参数,因为%
需要在参数值之内,而不是查询:
$sql = <<<'SQL'
UPDATE table
SET field = replace(field, :old_string, :value)
WHERE field LIKE :searchable_old_string
SQL;
Yii::app()->db->createCommand($sql)->execute([
'old_string' => $old_string,
'value' => $model->value,
'searchable_old_string' => "%$old_string%",
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.