【问题标题】:How do you use a variable in a $_POST[]如何在 $_POST[] 中使用变量
【发布时间】:2010-01-24 22:31:39
【问题描述】:

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

$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[] 中放入变量?如果没有,我应该如何更新动态生成的字段?

【问题讨论】:

    标签: php mysql post


    【解决方案1】:
    $_POST[$var] or $_POST["cst_$var"]
    

    【讨论】:

      【解决方案2】:

      不带单引号使用:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          $POST["cst$var"] - cst_$var 代表一个字符串

          正确答案是: $POST['cst'.$var]

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-04-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-30
            • 2013-12-05
            相关资源
            最近更新 更多