开发者

How do you use a variable in a $_POST[]

I need to iterate through a bunch of dynamically generated fields, but this doesn't work:

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

I have a list of locations with their populations on one page; I need to make it so you can update a lot of them at once. So I made the field names dynamically correspond to the location_id. When the post is submitted I need to iterate through them like so, but it seems you cannot put a variable in a post.

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_l开发者_JAVA百科ocation_id' ");
    }
}

Is it possible to put a variable inside a $_POST[]? If not, how should I go about updating dynamically generated fields?


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


Use it without the single quotes:

$_POST[$current_location_id]

Now the value of $current_location_id is used as key instead of the string $current_location_id. You can also use $current_location['ID'] directly:

$_POST[$current_location['ID']]

Even in your query:

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']."' ");
    }
}


Single quotes inhibit variable interpolation in a string; either use double quotes or omit them altogether.


$POST["cst$var"] - cst_$var represent a string

The corect answer is: $POST['cst'.$var]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜