tags:

views:

47

answers:

3

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

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

A: 

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']."' ");
    }
}
Gumbo
+1  A: 
$_POST[$var] or $_POST["cst_$var"]
Funky Dude
A: 

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

Ignacio Vazquez-Abrams