bindParam和bindValue的區別以及在Yii2中的使用

bindParam() 和 bindValue() 非常相似。唯一的區別就是前者使用一個 PHP 變量綁定參數, 而後者使用一個值。對於那些內存中的大數據塊參數,處於性能的考慮,應優先使用前者。

根據id查詢一條數據,並對id進行過濾:

$id = 1;
$result = Yii::$app->db->createCommand("select * from product where id=:id")->bindParam(":id",$id,\PDO::PARAM_INT)->queryAll();

$result = Yii::$app->db->createCommand("select * from product where id=:id")->bindParam(":id",$id,\PDO::PARAM_STR)->queryAll();

更新一條數據:

$id = 1;
$name = 'xiaoming';
$result = Yii::$app->db->createCommand("update product set name=:name where id=:id")->bindParam(':id',$id,\PDO::PARAM_INT)->bindParam(':name',$name,\PDO::PARAM_INT)->execute();

以下寫法在會報錯

$result = Yii::$app->db->createCommand()->delete('product',['name'=>':value'],'id=:id')->bindValue(':id',1,\PDO::PARAM_INT)->bindParam(':value',$user,\PDO::PARAM_INT)->execute();
發佈了122 篇原創文章 · 獲贊 40 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章