LoginSignup
1
1

More than 5 years have passed since last update.

Model::updateAllなどで自前でクォート&エスケープする方法

Last updated at Posted at 2017-05-30

CakePHP2のModel::updateAllでは値にクォートつけてくれません。

なので

$this->Item->updateAll(
    [
        'status' => 0,
        'modified' => date('Y-m-d H:i:s') // updateAllではmodifiedは自動更新されないので自分でセット
    ],
    [
        'email' => ''
    ]
);

こんな感じでmodified更新しようとかするとSQLエラーがおこります。

なので自前でクォートする必要があります。

この程度だったら

$this->Item->updateAll(
    [
        'status' => 0,
        'modified' => "'" . date('Y-m-d H:i:s') . "'" // updateAllではmodifiedは自動更新されないので自分でセット
    ],
    [
        'email' => ''
    ]
);

こなのでもOKですかね。

でもupdateAllに渡すのがPOSTされたパラメータとかだったらエスケープも必要ですよね。

で、エスケープについてググるとSanitize::escape()を使う方法がよくひっかかります。

ただ最近(2017/05/30現在)の公式ドキュメントだと DboSource::value()をつかえってなってるので、こっちを使った方がいいでしょう

$db = $this->getDataSource();
$value = $db->value($value, 'string');

そうして変更するとこうがいいですかね。

$this->Item->updateAll(
    [
        'status' => 0,
        'modified' => $this->getDataSource()->value(date('Y-m-d H:i:s')) 
    ],
    [
        'email' => ''
    ]
);

まとめ

Model::updateAll() には $this->getDataSource()->value() もセットでつかいましょう。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1