Ok, I'm using Yii2
and I'm familiar with preparing/binding data when using mysql queries, such as:
$sql = $this->db->createCommand("UPDATE some_table SET something='foo' WHERE some_id=:some_id");
$sql->bindValue(':some_id', $some_id);
But what about when the value may contain multiple values, such as when using the MySQL
syntax IN
?
For example:
$sql = $this->db->createCommand("UPDATE some_table SET something='foo' WHERE some_id IN (:parents)");
$sql->bindValue(':parents', $parents);
Now as I understand the above would only work well if the $parents
var only had one value; but if it had multiple values such as 1,2,3
then you would end up with something like '1,2,3'
when you really want '1','2','3'
OR 1,2,3
.
What is the correct way to do this?
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.
Binding sends the data to be inserted into MySQL separately from the query, and understands how to parse it for insertion without risking safety of the database. With the execute function, you just pass the array with keys corresponding to the placeholder data you defined in the prepare function.
use createcommand() method: use yii\db\Query(); $connection = \Yii::$app->db; $query = new Query; $insql = $connection->createCommand("SELECT* FROM inventory ); $result=$insql->queryAll(); the above method list all data from the inventory table.
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.
I've found this solution
$params = [];
$sql = \Yii::$app->db->getQueryBuilder()->buildCondition(['IN', 'some_id', $ids], $params);
//$sql = some_id NOT IN (:qp0, :qp1, :qp2)
//$params = [':qp0'=>1, ':qp1'=>2, ':qp2'=>3]
$this->db->createCommand("UPDATE some_table SET something='foo' WHERE $sql", $params);
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