Search code examples
mysqlyii2yii2-model

Inserting variables in Yii2 to Database


I am trying to insert $product, $pric and $user to database table cart. Following is the function that I have created in SiteController.php.

public function actionCartadd($id)
        {
                $product = Additem::find()
                        ->select('product')
                        ->where(['id' => $id])
                        ->one();
                $pric =  Additem::find()
                        ->select('price')
                        ->where(['id' => $id])
                        ->one();

                $user = Yii::$app->user->identity->username;


                $connection = Yii::$app->getDb();

                $result = Yii::$app->db->createCommand()
                        ->insert('cart', [
                        'product' => '$product',
                        'price' => '$pric',
                        'user' => '$user',
                        ])->execute();
                if ($result)
                         return $this->render('custstore');
        }

However, this end up in error. Can anyone suggest any fix


Solution

  • Try this following code

    $result = Yii::$app->db->createCommand()->insert('cart', [
        'product' => $product->product, 
        'price' => $pric->price,
        'user' => $user
    ])->execute();