I trying to use CDbCriteria with column named "key", which is a reserved word in MySQL:
public function search()
{
$criteria = new CDbCriteria;
$criteria->compare('key', $this->key);
$criteria->compare('position', $this->position);
$criteria->compare('dictionary', $this->dictionary);
return new CActiveDataProvider(get_class($this), array
(
'criteria'=>$criteria,
'pagination'=>array('pageSize'=>10),
'sort'=>array('defaultOrder'=>array('dictionary'=>FALSE, 'position'=>FALSE))
));
}
This, of course fails, when I’m trying to search/filter using “key” column:
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 'key LIKE '%2%')' at line 1. The SQL statement executed was: SELECT COUNT(*) FROM `lookup` `t` WHERE (dictionary LIKE :ycp0) AND (key LIKE :ycp1)
I found some solution at Stack Overflow:
$criteria->condition = 't.key=:key';
$criteria->params = array(':key'=>$this->key);
$criteria->compare('position', $this->position);
$criteria->compare('dictionary', $this->dictionary);
However, this works for me only partially. I don’t get exception anymore, but search works for “key” column only. All other are ignored (if “key” is set, respects only this value in search, if it is not set – always returns empty results set).
What am I missing? How should I construct CDbCriteria queries, when my table contains reserverd words as column names, so search would respect all other (non-reserved) columns as well, not only this one?