Addincondition And Condition With Params

Hiya,

It took a bit of time for me to work this out so it might help someone.

I was having a great trouble with CDbCriteria having a condition, a addInCondition and a params for the condition field.

I was using this code


		$criteria = new CDbCriteria;

		$criteria->condition = 'period=:period';

		$criteria->addInCondition('number',$numbers);

		$criteria->params = array(':period'=>$period);

I was getting this error


CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: SELECT COUNT(*) FROM `data` `t` WHERE (period=:period) AND (number IN (:ycp0, :ycp1, :ycp2, :ycp3, :ycp4, :ycp5))

I found the only solution was to change it so the params were specified straight after the condition and before the addInCondition like this:


$criteria = new CDbCriteria;

		$criteria->condition = 'period=:period';

		$criteria->params = array(':period'=>$period);

		$criteria->addInCondition('number',$numbers);

This then worked.

Hope this helps someone.

Dear Friend

Yes you are absolutely correct.

This happens because method CDbCriteria::addInCondition internally creates the params for each element in the array.

If we declare the params at the end of code, we are completely resetting the params overiding parameters set

in the method CDbCriteria::addInCondition.

To circumvent this we have to do the following.




$criteria = new CDbCriteria;

$criteria->condition = 'period=:period';

$criteria->addInCondition('number',$numbers);

$criteria->params = array(':period'=>$period)+$criteria->params;//+ array union operator



Regards.

Excellent fix regarding the overwriting of parameters, just spent 2.5 hours trying to work out what was going on. Your post just made it all work. Thanks! :D