也就是说,我将遵循避免 sql 注入(inject)的良好实践。所以这不好:
$query="SELECT id,tag FROM tbl_tags WHERE tag LIKE '%".$tag."%' ORDER BY creation_time DESC LIMIT 0,10 ";
相反,我必须使用参数绑定(bind):
$query="SELECT id,tag FROM tbl_tags WHERE tag LIKE :tag ORDER BY creation_time DESC LIMIT 0,10 ";
$command =Yii::app()->db->createCommand($query);
$command->bindParam(":tag", "%{$tag}%", PDO::PARAM_STR);
$models = $command->queryAll();
但这会生成: fatal error :无法通过引用传递参数 2
如何绑定(bind)这个面向 LIKE 的参数?
最佳答案
尝试使用查询生成器。因此您的查询将如下所示:
Yii::app()->db->createCommand()
->select('id, tag')
->from('tbl_tags')
->where('tag like :tag', array(':tag' => "%{$tag}%"))
->order('creation_time desc')
->limit('0, 10')
->queryAll()
如果您正在寻找良好的实践,那就更好了。
P.S.:从 iPhone 回复,请原谅拼写错误。
关于sql - 无法将参数绑定(bind)到 CDbCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16727153/