使用 in_array() 清理 SQL 和 PHP 中的查询

Sanitise query in SQL and PHP using in_array()

使用 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 注入是安全的,因为 属性 值与查询分开处理。

但是,如果我想使用相同的代码编写可能检索不同字段或不同分组的查询,则不能单独使用 prepare/execute 方法,因为不能对字段使用 PDO 参数(see here).

你能简单地使用 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);

有没有更安全/更快捷的方法?

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

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

$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;

function benchmarks