How to use 'IN (1,2,3)' with findAll?

oldwizard picture oldwizard · May 10, 2011 · Viewed 22.2k times · Source

I need to get a couple of Students from the database, and I have their primary keys in a comma-separated string.

Normally using SQL it would be something like:

$cleanedStudentIdStringList = "1,2,3,4";
SELECT * FROM Student WHERE id IN ($cleanedStudentIdStringList)

Yii's ActiveRecord seems to insert a single quote around bound parameters in the resulting SQL statement which cause the query to fail when using parameter binding.

This works, but doesn't use safe parameter binding.

$students = Student::model()->findAll("id IN ({$_POST['studentIds']})");

Is there a way to still use parameter binding and get only a couple of rows in a single query?

Answer

Aleksy Goroszko picture Aleksy Goroszko · May 10, 2011

You can do it also that way:

$criteria = new CDbCriteria();
$criteria->addInCondition("id", array(1,2,3,4));
$result = Student::model()->findAll($criteria);

and use in array any values you need.

Aleksy