How to use IN/AND clause in Yii framework?

mysql-error-1064, yii

Solution

Try this

$criteria = new CDbCriteria();
$criteria->select = "*";
$criteria->condition = "idname = :name ";
$criteria->params = array ( 
':name' => $name,
);
$criteria->addInCondition('user', $arrayOfUsers);
my_table::model()->findAll($criteria);

Problem

I have a MySQL table with 3 columns: ID, name, user. I wish to use the following SQL with Yii framework: ``` $sql = "SELECT * FROM my_table WHERE idName=".$name." AND user IN .$arrayOfUsers; // $arrayOfUsers is an array of int [0]->1, etc. ``` I tried in three different ways, but without success: 1) ``` $sql = "SELECT * FROM my_table WHERE idName=".$name." AND user IN .$arrayOfUsers; $command = $connection->createCommand($sql); $dataReader = $command->query(); $query = $dataReader->readAll(); ``` The error is: PHP Error [8] Array to string conversion 2) ``` $query = Yii::app()->db->createCommand() ->select('*') ->from('my_table') ->where(array('and', array('in', 'user', $arrayOfUsers), array('idName' => $name))) ->queryAll(); ``` The error is: PHP Error [8] Undefined offset: 0 3) ``` $query = Yii::app()->db->createCommand() ->select('*') ->from('my_table') ->where(array('and', array('in', 'user', $arrayOfUsers), 'idName='.$name))) ->queryAll(); ``` The error is: CDbException 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 'idName=7)' at line 3. The SQL statement executed was: SELECT * FROM `my_table` WHERE (`user` IN ('1', '2', '3', '4')) AND (idName=7)

Original source