0

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

1
  • 1
    What error? Please show us Commented Nov 21, 2019 at 7:33

2 Answers 2

1

Try this following code

$result = Yii::$app->db->createCommand()->insert('cart', [
    'product' => $product->product, 
    'price' => $pric->price,
    'user' => $user
])->execute();
Sign up to request clarification or add additional context in comments.

Comments

0

Look at this fragment:

'product' => '$product',
'price' => '$pric',
'user' => '$user',

Use double quotes in values or just variables without quotes

Also, better way to fetch product and price:

$productItem = Additem::findOne($id);
if ($productItem instanceof Additem) {
    $product = $productItem->product;
    $pric = $productItem->price;
}

2 Comments

I am trying to insert the contents to the database table and I am not trying to fetch it. Also marking the values using double quotes or without any quotes didn't work.
He meana you don't need to call two times the function find. you can get the Model as he write in the answer and get all properties of the Model. It's better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.