你如何在$ _POST []中使用变量

时间:2010-01-24 22:31:40

标签: php mysql post

我需要遍历一堆动态生成的字段,但这不起作用:

$population_density = $_POST['$current_location_id'];

我在一页上列出了人口名单;我需要这样做,这样你就可以立刻更新它们。所以我使字段名称动态地对应于location_id。提交帖子时,我需要像这样迭代它们,但似乎你不能把一个变量放在帖子里。

for ( $y_count = 1 ; $y_count <= $zone_height; $y_count++ ) {
    for ( $x_count = 1 ; $x_count <= $zone_width; $x_count++ ) {
        $result = mysql_query("SELECT * FROM locations WHERE location_zone='$zone_id' AND x_location='$x_count' AND y_location='$y_count' ");
        $current_location = mysql_fetch_array( $result );
        $current_location_id = $current_location['ID'];
        $population_density = $_POST['$current_location_id'];
        $result = mysql_query("UPDATE locations SET population_density='$population_density' WHERE ID='$current_location_id' ");
    }
}

是否可以将变量放在$ _POST []中?如果没有,我该如何更新动态生成的字段?

4 个答案:

答案 0 :(得分:2)

$_POST[$var] or $_POST["cst_$var"]

答案 1 :(得分:1)

使用它而不使用单引号:

$_POST[$current_location_id]

现在$current_location_id的值用作键而不是字符串$current_location_id。您也可以直接使用$current_location['ID']

$_POST[$current_location['ID']]

即使在您的查询中:

for ( $y_count = 1 ; $y_count <= $zone_height; $y_count++ ) {
    for ( $x_count = 1 ; $x_count <= $zone_width; $x_count++ ) {
        $result = mysql_query("SELECT * FROM locations WHERE location_zone='$zone_id' AND x_location='$x_count' AND y_location='$y_count' ");
        $current_location = mysql_fetch_array( $result );
        $result = mysql_query("UPDATE locations SET population_density='".$_POST[$current_location['ID']]."' WHERE ID='".$current_location['ID']."' ");
    }
}

答案 2 :(得分:1)

单引号禁止字符串中的变量插值;使用双引号或完全省略它们。

答案 3 :(得分:0)

$ POST [&#34; cst $ var&#34;] - cst_ $ var代表一个字符串

核心答案是: $ POST [&#39; CST &#39; $变种]