使用MySQL和PHP,典型的(PDO)查询如下所示:
有更安全/更快的方法吗?
// prepare the query
$q = $DB->prepare("SELECT * FROM table_name WHERE property = :value");
// run the query
$q->execute(array(':value'=>$value));
这是安全的防止SQL注入的做法,因为属性值与查询是分开处理的。
但是,如果我想使用相同的代码编写查询以检索不同的字段或不同的分组,仅使用准备/执行方法是不够的,因为您不能使用PDO参数来处理字段 (请参见此处).
您可以像这样使用in_array()函数来检查字段名:
// return false if the field is not recognised
if(! in_array($field_name, array('field1','field2','field3')) return false
// run the query
$q = $DB->query("SELECT * FROM table_name ORDER BY " . $field_name);
有更安全/更快的方法吗?