gpt4 book ai didi

php - 使用 in_array() 在 SQL 和 PHP 中清理查询

转载 作者:可可西里 更新时间:2023-11-01 08:27:52 28 4
gpt4 key购买 nike

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

但是,如果我想使用相同的代码编写可能检索不同字段或不同分组的查询,则不能单独使用准备/执行方法,因为不能对字段使用 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

关于php - 使用 in_array() 在 SQL 和 PHP 中清理查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33258029/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com