doushan2311 2013-01-08 19:07
浏览 106
已采纳

使用动态命名循环遍历多个POST变量

I hope this makes sense in relation to the title and what I'm trying to achieve, so here goes...

I have a form that displays between 1 to 30 fields to be entered - the number of fields is determined by the user at a previous stage (it will not always be the same amount).

If a user has 5 fields to fill out, they must all contain data - the same if they set 15 fields or 30 fields.

What I want to be able to do is loop through the POST variables in the form, make sure they are all set and either insert the data to the database, or display an error.

I was going to do 30 if statements with nested if statements:

if ($numberOfFields == 1){
    if (!$_POST["field1_text"]){$error = 1;}
};

if ($numberOfFields == 2){
    if (!$_POST["field1_text"]){$error = 1;}
    if (!$_POST["field2_text"]){$error = 1;}
};

But this seems a very long winded way and I was wondering if anyone had any suggestions or pointers.

I was wondering if something like this would work:

for ($q = 1; $q <= $numberOfFields; $q ++){
    if (!$_POST["field'".$q."'_text"]){
        $error = 1;
    }   
}

But I'm getting an error referencing the variable/field name using the $q. Should this be [$q] or something else?

I'm struggling to find any answers, but probably not asking the right question, but any help would be appreciated.

Thanks

  • 写回答

2条回答 默认 最新

  • duandange7480 2013-01-08 19:10
    关注

    Use this:

    for ($q = 1; $q <= $numberOfFields; $q++){
        if (!$_POST["field".$q."_text"]){
            $error = 1;
        }   
    }
    

    In your own code you had weird extra '

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘