Home > Net >  Yii2 createCommand with params
Yii2 createCommand with params

Time:03-02

I need count my cart items in db, cart items without model. Trying like this:

$id = Yii::$app->request->post('id');
$total = Yii::$app->db->createCommand('SELECT COUNT(*) FROM cart_items WHERE user_id="'.$id.'"')->queryScalar();

Return 0, but have 2 rows.

$total = Yii::$app->db->createCommand('SELECT COUNT(*) FROM cart_items WHERE user_id="19"')->queryScalar();

Return 2.

How to bind my params right with post data?

Update:

public function beforeAction($action) {
        $this->enableCsrfValidation = false;
        if (parent::beforeAction($action)){
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return true;
        }
        return false;
    }
public function behaviors()
    {
        return [            
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'checkout' => ['post','get'],
                ],
            ],
        ];
    }

CodePudding user response:

You could use bindValues()

  $total = Yii::$app->db->createCommand('SELECT COUNT(*) 
         FROM cart_items WHERE user_id=:id')
    ->bindValues([':id'=>$id)
    ->queryScalar();
  • Related