Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 599
oldwizard Avatar asked May 10 '11 08:05

oldwizard


2 Answers

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

like image 144
Aleksy Goroszko Avatar answered Oct 03 '22 16:10

Aleksy Goroszko


You can use findAllByAttributes method also:

$a=array(1,2,3,4);
$model = Student::model()->findAllByAttributes(array("id"=>$a));
like image 25
nsv Avatar answered Oct 03 '22 15:10

nsv