Yii createCommand更新多个记录的字符串的一部分

时间:2018-08-13 11:46:09

标签: php yii sqlite

我正在使用createCommand替换多个记录的字段中的一部分字符串。 以下代码效果很好:

Yii::app()->db->createCommand("UPDATE table SET field=replace(field,'" . $old_string . "','" . $model->value . "') WHERE field LIKE '%" . $old_string . "%'")->execute();

(Yii 1.1)

但是,如何参数化它,以便可以使用:oldString和:newString,而不是将变量直接链接到查询?

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用绑定参数

$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();

答案 1 :(得分:0)

您只需要在查询中用参数占位符替换值,然后将实际值传递给func countSwaps(a: [Int]) -> Void { var result = a var numberOfSwaps = 0 let length = a.count for i in 0 ..< length - 1 { for j in 0 ..< length - 1 - i { if result[j] > result[j + 1] { result.swapAt(j, j + 1) numberOfSwaps += 1 } } } print("Array is sorted in \(numberOfSwaps) swaps.") print("First Element: \(result.first!)") print("Last Element: \(result.last!)") } 。唯一棘手的部分是execute()的参数,因为LIKE必须在参数值之内,而不是查询:

%