我试图在我的yii应用程序上获取时间范围。
这是我的模特:
public function timeRange($attribute, $params) {
$criteria = new CDbCriteria;
$criteria->addCondition(
"WHERE ('jam_keluar' > '{$this->jam_masuk}' OR 'jam_masuk' < '{$this->jam_keluar}')".
"OR ('jam_masuk' < '{$this->jam_keluar}' AND 'jam_keluar' > '{$this->jam_keluar}')"
);
$record = self::model()->exists($criteria);
if(!empty($record)) {
$this->addError('jd_id', 'Item already exists within range.');
return false;
}
}
但我收到以下错误:
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ('jam_keluar' > 03:00:00' OR 'jam_masuk' < '12:00:00')OR ('jam_masuk' < '1' at line 1. The SQL statement executed was: SELECT 1 FROM `a_jadwal` `t` WHERE WHERE ('jam_keluar' > 03:00:00' OR 'jam_masuk' < '12:00:00')OR ('jam_masuk' < '12:00:00' AND 'jam_keluar' > '12:00:00') LIMIT 1
任何?
答案 0 :(得分:2)
您需要删除&#39; WHERE&#39;从你的addCondition中,因为addCondition将为你处理。也可以使用引号转义所有值,但不要在列名称周围添加引号。
你应该使用CDbCriteria :: compare或者至少使用addCondition和params来避免SQL注入:
// Use the solution with CDbCriteria::addCondition
$criteria->addCondition(
"WHERE (jam_keluar > :jam_masuk OR jam_masuk < :jam_keluar)".
"OR (jam_masuk < :jam_keluar AND jam_keluar > :jam_keluar)",
array(
':jam_masuk' => $this->jam_masuk,
':jam_keluar' => $this->jam_keluar
)
);
// Or use the solution with CDbCriteria::compare
$criteria->compare('jam_keluar', '>'.$this->jam_masuk, false);
$criteria->compare('jam_masuk', '<'.$this->jam_keluar, false, 'OR');
$criteria->compare('jam_masuk', '<'.$this->jam_keluar, false, 'OR');
$criteria->compare('jam_keluar', '>'.$this->jam_keluar, false);
答案 1 :(得分:0)
缺少单引号。
$criteria->addCondition(
"WHERE ('jam_keluar' > '{$this->jam_masuk}' OR 'jam_masuk' < '{$this->jam_keluar}')".
"OR ('jam_masuk' < '{$this->jam_keluar}' AND 'jam_keluar' > '{$this->jam_keluar}')"
);
这里:
"WHERE ('jam_keluar' > {$this->jam_masuk}' ...
答案 2 :(得分:0)
公共函数timeRange($ attribute,$ params){
$criteria = new CDbCriteria;
$criteria->addCondition(
"WHERE ('jam_keluar' > '{$this->jam_masuk}' OR 'jam_masuk' < '{$this->jam_keluar}')".
"OR ('jam_masuk' < '{$this->jam_keluar}' AND 'jam_keluar' > '{$this->jam_keluar}')"
);
$record = self::model()->exists($criteria);
if(!empty($record)) {
$this->addError('jd_id', 'Item already exists within range.');
return false;
}
else {
return true;
}
}
您错过了 ' 内部查询