为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
精慕HU 2022-09-17 17:33:05
想要将动态 GET 变量转换为两个内部变量,以便我可以在 SQL 查询中使用这些值。我正在将变量字符串传递给这样的URLhttp://localhost/api-data?serial=1923473http://localhost/api-data?manufacturer=jaguarhttp://localhost/api-data?location=londonhttp://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";提前感谢您。
查看完整描述

4 回答

?
慕标5832272

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 注入。在这种情况下,解决此问题的最佳选择是使用有效密钥列表验证每个密钥。


查看完整回答
反对 回复 2022-09-17
?
慕的地8271018

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]);

}


查看完整回答
反对 回复 2022-09-17
?
慕容森

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"


查看完整回答
反对 回复 2022-09-17
?
牛魔王的故事

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

?>


查看完整回答
反对 回复 2022-09-17
  • 4 回答
  • 0 关注
  • 181 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号