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?
$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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With