Yii IN Query不起作用

时间:2013-12-23 12:45:11

标签: php mysql yii

我正在尝试在yii中创建一个查询,但它没有提供所需的输出但是抛出错误

 $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);

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

注意: - $mydata is dynamic

如果我尝试这个

"productName IN $mydata"然后它完美地工作

2 个答案:

答案 0 :(得分:3)

您似乎错误地构建了where子句。以下是如何使用输入范围执行WHERE子句的列表:

// 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%')))

查看the Yii query builder article/guide

所以,为了让它适合你...试试这个:

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

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

var_dump($records);

答案 1 :(得分:1)

试试这个......

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

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

var_dump($records);