Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind array parameters in Yii framework?

Tags:

php

yii

yii1.x

I have below code:

$inputs = "1,2,3,4,5";
$sql = "SELECT * FROM obj WHERE id IN(:input)";

$commond = Yii::app()->db->createCommand($sql);
$commond->bindValue(":input", $inputs , PDO::PARAM_STR);

But the query result is incorrect. How to bind params for such IN condition?

like image 414
Cherry Avatar asked Mar 02 '12 07:03

Cherry


People also ask

What is $App in Yii?

$app=Yii::createWebApplication($configFile); Tip: If the application configuration is very complex, we can split it into several files, each returning a portion of the configuration array.

How to write SQL query in Yii2?

Call yii\db\QueryBuilder to generate a SQL statement based on the current construct of yii\db\Query; Create a yii\db\Command object with the generated SQL statement; Call a query method (e.g. queryAll()) of yii\db\Command to execute the SQL statement and retrieve the data.

Is null in Yii2 query?

Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.

What is Query Builder in Yii2?

The Yii Query Builder provides an object-oriented way of writing SQL statements. It allows developers to use class methods and properties to specify individual parts of a SQL statement.


2 Answers

for now use it like this

$command = Yii::app()->db->createCommand()
    ->select()
    ->from('tableName')
    ->where(array('in', 'id', explode(',', $inputs)));

I ll try to get back with $command->bindValue() method.

like image 178
Uday Sawant Avatar answered Oct 20 '22 22:10

Uday Sawant


Having come across this problem a few times in my projects I have come-up with the following Yii work-around using CDbCriteria which is a little hacky, but gives the security of param count matching.

When applied to your example my code would be:

$inputs = array(1,2,3,4,5);
$criteria = new CDbCriteria();
$criteria->addInCondition('id',$inputs);

$sql = 'SELECT * FROM obj WHERE '.$criteria->condition;
$command = Yii::app()->db->createCommand($sql);
$results = $command->queryAll(true, $criteria->params);

UPDATE

There is actually a much cleaner way to do this built into Yii:

$results = Yii::app()->db->createCommand()
   ->select()
   ->from('obj')
   ->where(['in', 'id', $inputs])
   ->queryAll();

See Docs

like image 7
Arth Avatar answered Oct 20 '22 22:10

Arth