在SQL和PHP中使用in_array()来清理查询。

3
使用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);

有更安全/更快的方法吗?

2
它足够安全。还有更好的解决方案,例如当您拥有具有定义字段的实体/模型时,但在in_array中也可以使用;) - Daimos
1个回答

2

看起来已经相当快和安全了。也许在查询中的字段名称周围添加反引号。

为了稍微加快速度,您可以使用关联数组,并仅检查索引是否存在,而不是搜索数组的内容。

$fields = array('field1' => null, 'field2' => null, 'field3' => null);
if (!array_key_exists($field_name, $fields)) return false;

此外,isset比array_key_exists更快。
if (!isset($fields[$field_name])) return false;

功能基准测试


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接