Let me see
Let me see

Reputation: 5094

Yii IN Query is not working

I am trying to create a query in yii but its not giving the desired output but throws error

 $name=array('tata','classmate');
    //  $result=  implode(',', $name);
    $mydata='("tata","classmate","adas")';
    $records=Yii::app()->db->createCommand()->select('productName')->from('products')->where
("productName IN :name",array(':name'=>$mydata))->queryColumn();
    var_dump($records);

Error:-MySQL server version for the right syntax to use near ''(\"tata\",\"classmate\",\"adas\")'' at line 3

Note:- $mydata is dynamic

if I try this

"productName IN $mydata" then its working perfectly

Upvotes: 1

Views: 97

Answers (2)

Latheesan
Latheesan

Reputation: 24116

It appears you are incorrectly building the where clause. Here's a list of how to do WHERE clause with input range:

// WHERE id=1 or id=2
where('id=1 or id=2')
// WHERE id=:id1 or id=:id2
where('id=:id1 or id=:id2', array(':id1'=>1, ':id2'=>2))
// WHERE id=1 OR id=2
where(array('or', 'id=1', 'id=2'))
// WHERE id=1 AND (type=2 OR type=3)
where(array('and', 'id=1', array('or', 'type=2', 'type=3')))
// WHERE `id` IN (1, 2)
where(array('in', 'id', array(1, 2))
// WHERE `id` NOT IN (1, 2)
where(array('not in', 'id', array(1,2)))
// WHERE `name` LIKE '%Qiang%'
where(array('like', 'name', '%Qiang%'))
// WHERE `name` LIKE '%Qiang' AND `name` LIKE '%Xue'
where(array('like', 'name', array('%Qiang', '%Xue')))
// WHERE `name` LIKE '%Qiang' OR `name` LIKE '%Xue'
where(array('or like', 'name', array('%Qiang', '%Xue')))
// WHERE `name` NOT LIKE '%Qiang%'
where(array('not like', 'name', '%Qiang%'))
// WHERE `name` NOT LIKE '%Qiang%' OR `name` NOT LIKE '%Xue%'
where(array('or not like', 'name', array('%Qiang%', '%Xue%')))

Have a look at the Yii query builder article/guide.

So, to make it work for you.. try this:

$mydata = array('tata','classmate', 'adas');

$records = Yii::app()->db->createCommand()
    ->select('productName')
    ->from('products')
    ->where(array('in', 'productName', $mydata)
    ->queryColumn();

var_dump($records);

Upvotes: 3

naveen goyal
naveen goyal

Reputation: 4629

Try this...

$mydata = array('tata','classmate', 'adas');

$records = Yii::app()->db->createCommand()
    ->select('productName')->from('products')
    ->where(array('in', 'productName', $mydata))
    ->queryColumn();

var_dump($records);

Upvotes: 1

Related Questions