Search code examples
phpsqlyiicriteria

Using Yii's CDbCriteria's compare method with empty strings


I am making a new Yii CDbCriteria, and want to add the following condition:

$criteria = new CDbCriteria();
$criteria->compare('code', $code);

However, in my application, the variable $code can be an empty string. I read in the documentation:

When the value is empty, no comparison expression will be added to the search condition.

This is not desired behavior for me. I want it to compare with an empty string. Is there a way to accomplish this using compare?

Could I instead also use the following query? Is it safe?

$criteria->addCondition("code = $code");

If so, what are the drawbacks/benefits between compare and addCondition?


Solution

  • CDbCriteria::compare() is a shortcut wrapper for addCondition (the latter is called within its body anyway). The method is designed so that it covers the most common use-cases of processing the filter criteria; that's why it ignores the 'non-meaningful' input. As your case is outside the covered area, you should use the low-level addCondition, but with a twist:

    $criteria->addCondition('code = :code');
    $criteria->params[':code'] = $code;
    

    You can also use another shortcut method:

    $criteria->addColumnCondition(array('code' => $code));