Brett Brett - 1 year ago 138
PHP Question

Correct way to bind parameters using MySQL "IN" syntax in Yii2?

Ok, I'm using

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

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
var only had one value; but if it had multiple values such as
then you would end up with something like
when you really want

What is the correct way to do this?

Answer Source

I ended up doing it like this:

$parents_safe = '';
$parents_sep = explode(',', $parents);

foreach ($parents_sep as $parent) {
    $parents_safe .= $this->db->quoteValue($parent) . ',';

$parents_safe = rtrim($parents_safe, ',');

Where $this->db is an instance of Yii::$app->db.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download