声明表单变量和数组

时间:2015-11-13 12:01:14

标签: php arrays

我正在尝试从表单(post)声明变量和数组,但似乎数组没有被处理:

// is this a better practise than directly pass the entire $_POST?
$list = array('use', 'type', 'status', 'bhk', 'baths', 'size', 'location', 'price', 'description');
foreach($list as $name) {
    if ($name != 'description')
        $var = "\$" . $name . "=filter_input(INPUT_POST, '" . $name . "', FILTER_SANITIZE_NUMBER_INT);";
    else if ($name == 'description')
        $var = "\$" . $name . "=filter_input(INPUT_POST, '" . $name . "', FILTER_SANITIZE_STRING);";
}

$area_1 = $size['area1'] != '' ? $size['area1'] : 0;
$area_2 = $size['area2'] != '' ? $size['area2'] : 0;
$city   = $location['city'];
$zone   = $location['zone'];
$sale   = $price['sale'] != '' ? $price['sale'] : 0;
$rent   = $price['rent'] != '' ? $price['rent'] : 0;

可能有些投入是长数吗?与$price['sale'](最高999999)或$size['area1'](最高999)相同。由于它们不需要任何单元类型,我更喜欢将它们存储为整数而不是字符串。但请告诉我长度是否有问题。

编辑:(在评论中由@ swidmann 修改)

$$name = filter_input(INPUT_POST, $name, FILTER_SANITIZE_NUMBER_INT);

解决方案:(在评论中通过@ swidmann

$$name = filter_input(INPUT_POST, $name, FILTER_DEFAULT , FILTER_REQUIRE_ARRAY)

1 个答案:

答案 0 :(得分:1)

要从数组创建变量,您应该使用$$而不是将字符串与运行eval()连接起来,因为eval() is evil

你可以制作这样的变量:

使用$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT );

$$name您可以使用字符串内容$nam e

的名称定义变量

如果您的输入可以是数组,请使用FILTER_REQUIRE_ARRAY选项查看filter_input_array()filter_input(),具体取决于您的需要。

以下是一种方法:

// is this a better practise than directly pass the entire $_POST?
$list = array( 'use', 'type', 'status', 'bhk', 'baths', 'size', 'location', 'price', 'description' );
foreach ( $list as $name ) {
    if ( $name != 'description' ) {
        if( is_array( $_POST[$name] ) ) {
            // I think you should also check for other types if needed (i.e. string)
            $$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT , FILTER_REQUIRE_ARRAY );
        } else {
            $$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT  );
        }
    } else if ( $name == 'description' ) {
        $$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_STRING );
    }
}

$area_1 = $size['area1'] != '' ? $size['area1'] : 0;
$area_2 = $size['area2'] != '' ? $size['area2'] : 0;
$city = $location['city'];
$zone = $location['zone'];
$sale = $price['sale'] != '' ? $price['sale'] : 0;
$rent = $price['rent'] != '' ? $price['rent'] : 0;

如果您不确定输入,可以尝试FILTER_DEFAULT选项:

$$name = filter_input(INPUT_POST, $name, FILTER_DEFAULT , FILTER_REQUIRE_ARRAY)