PHP 获取或将数据发布到变量中,包括

想要将动态 GET 变量转换为两个内部变量,以便我可以在 SQL 查询中使用这些值。


我正在将变量字符串传递给这样的URL


http://localhost/api-data?serial=1923473

http://localhost/api-data?manufacturer=jaguar

http://localhost/api-data?location=london

http://localhost/api-data?country=uk

我想将GET数据转换为两个不同的变量,例如串行变为$data 1,1923473变为$data 2。GET数据总是以上述格式,我只想转换为两个不同的变量。


print_r($_GET);

我可以看到变量像数组一样传递。我的问题是,如果数据以以下格式传递 AAAAA=BBBBB 作为获取变量,我如何将 AAAAA 转换为变量 $data 1,将 BBBBBB 转换为 £data2。请记住,GET 数据将始终是唯一的。


一旦我在2个唯一变量中拥有了这些数据,我就想运行一个SQL查询。


select blah1, blah2, blah4, blah5 from datastore where $data1 = "$data2";

提前感谢您。


精慕HU
浏览 182回答 4
4回答

慕标5832272

$_GET是传递的所有参数的数组。因此,的 URL 将导致?abc=def&foo=bar$_GETarray(2) {     ["abc"]=> string(3) "def"     ["foo"]=> string(3) "bar" }使用此功能,您可以遍历每个项目并将其附加到查询中:foreach($_GET as $key => $val) {    $query .= " AND $key = '$val'";}但是,请确保考虑 SQL 注入。在这种情况下,解决此问题的最佳选择是使用有效密钥列表验证每个密钥。

慕的地8271018

您的方法不是最好的,当您有多个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]);}

慕容森

这是以简单明了的声明性方式执行此操作的一种方法。我强烈建议检查 PDO 和 PDO 语句来构建查询。没有添加此示例,因为它不是问题。<?php// given&nbsp;$_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) {&nbsp; &nbsp; return in_array($key, $allowedVariables);}, ARRAY_FILTER_USE_BOTH);// create an array of strings like "$data1 = $data2"$query = array_map(function ($key, $value) {&nbsp; &nbsp; 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"

牛魔王的故事

为此,您可以使用(阅读有关 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);?>
打开App,查看更多内容
随时随地看视频慕课网APP