yii2

How to bind parameters with yii2 CreateCommand


When i run this code:

 $params = [':idCollection' => $idCollection, ':idBlock' => $idBlock];
            //dd($params);
            Yii::$app->db->createCommand()->insert('collectionxblock', [
                'id_collection' => ':idCollection',
                'id_block' => ':idBlock',
            ])->bindValues($params)->execute();

I get this error:

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens The SQL being executed was: INSERT INTO collectionxblock (id_collection, id_block) VALUES (0, 0) How can i bind Parameters with insert query ?


Solution

  • You don't need to explicitly create params and bind them when using query builder or methods like yii\db\Command::insert() or yii\db\Command::update(). The framework will take care of params.

    You only need to pass columns and values as array:

    Yii::$app->db->createCommand()->insert('collectionxblock', [
        'id_collection' => $idCollection,
        'id_block' => $idBlock,
    ])->execute();
    

    Methods that works with params are available if you want to or need to write SQL query yourself. For example:

    Yii::$app->db->createCommand(
        'INSERT INTO collectionxblock (id_collection, id_block) VALUES (:idCollection, :idBlock)'
    )->bindValues($params)
        ->execute();