bindParam与bindValue的核心区别
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();
上述关于bindParam和bindValue的区别以及在Yii2中的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。