声明表单变量和数组


declare form variables and 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)

要从数组中创建变量,应该使用$$,而不是连接字符串并运行eval(),因为eval()是邪恶的。

你可以制作这样的变量:

$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT );$$name您可以定义一个具有字符串内容名称的变量$nam e

如果您的输入可以是数组,请查看filter_put_array()或filter_put(),选项为FILTER_REQUIRE_ARRAY,这取决于您需要什么。

这里有一种方法:

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