4 回答
TA贡献1966条经验 获得超4个赞
$_GET是传递的所有参数的数组。因此,的 URL 将导致?abc=def&foo=bar$_GET
array(2) {
["abc"]=> string(3) "def"
["foo"]=> string(3) "bar"
}
使用此功能,您可以遍历每个项目并将其附加到查询中:
foreach($_GET as $key => $val) {
$query .= " AND $key = '$val'";
}
但是,请确保考虑 SQL 注入。在这种情况下,解决此问题的最佳选择是使用有效密钥列表验证每个密钥。
TA贡献1796条经验 获得超4个赞
您的方法不是最好的,当您有多个GET变量时,需要重新设计,但通常:
$allowed = ['serial', 'manufacturer']; //etc...
$col = key($_GET);
if(in_array($col, $allowed)) {
$val = $_GET[$col];
//Then prepare and execute using whatever DB library you are using
$st = $db->prepare("SELECT blah1, blah2, blah4, blah5 FROM datastore WHERE $col = ?");
$st->execute([$val]);
}
TA贡献1853条经验 获得超18个赞
这是以简单明了的声明性方式执行此操作的一种方法。
我强烈建议检查 PDO 和 PDO 语句来构建查询。没有添加此示例,因为它不是问题。
<?php
// given
$_GET = ['serial' => 342, 'something-else' => 'not used'];
$allowedVariables = ['serial', 'manufacturer', 'location', 'country'];
// filter values from the query for only allowed keys
$data = array_filter($_GET, function ($value, $key) use ($allowedVariables) {
return in_array($key, $allowedVariables);
}, ARRAY_FILTER_USE_BOTH);
// create an array of strings like "$data1 = $data2"
$query = array_map(function ($key, $value) {
return "$key = $value";
}, array_keys($data), array_values($data));
// build the query while combining values with the "AND" keyword
$query = "select * from datastore where " . implode(' and ', $query);
var_dump($query);
// string(42) "select * from datastore where serial = 342"
TA贡献1830条经验 获得超3个赞
为此,您可以使用(阅读有关 php.netextract($inputArray))
输入数组中的键将成为变量名称,其值将分配给这些新变量。
此外,如果要筛选键,以便有人不会在您当前的作用域中注入不需要的变量,请在调用函数之前执行以下操作...extract()
<?php
// Pick only the data keys that are expected. Their names must be compatible with the PHP variable naming conventions.
$filteredData = array_intersect_key($_GET /* or $_POST*/, array_flip(['serial', 'manufacturer', 'location', 'country']));
// Extract the names into variables in the current scope.
extract($filteredData);
?>
- 4 回答
- 0 关注
- 181 浏览
添加回答
举报
