要有效的防止SQL注入问题,我们建议:
- 查询条件尽量使用数组方式,这是更为安全的方式;
- 如果不得已必须使用字符串查询条件,使用预处理机制;
- 使用自动验证和自动完成机制进行针对应用的自定义过滤;
- 如果环境允许,尽量使用PDO方式,并使用参数绑定。
查询条件预处理
where方法使用字符串条件的时候,支持预处理(安全过滤),并支持两种方式传入预处理参数,例如:
$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();
// 或者
$Model->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)->select();
模型的query和execute方法 同样支持预处理机制,例如:
$model->query('select * from user where id=%d and status=%d',$id,$status);
//或者
$model->query('select * from user where id=%d and status=%d',array($id,$status));
execute方法用法同query方法。
看到这里,大家也许对预处理的‘%d','%s'等有些不理解,大家具体可以参考vsprintf()方法的参数说明:
http://www.w3school.com.cn/php/func_string_vsprintf.asp