使用动态命名循环遍历多个POST变量 [英] Loop through multiple POST variables using dynamic naming

查看:116
本文介绍了使用动态命名循环遍历多个POST变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这对标题和我想要实现的目标有意义,所以这里...

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

我有一个表格,显示要输入的1到30个字段-字段数由用户在上一个阶段确定(数量不一定总是相同的).

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).

如果用户有5个字段要填写,则他们都必须包含数据-如果设置了15个字段或30个字段,则必须相同.

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

我想做的是遍历表单中的POST变量,确保它们都已设置,然后将数据插入数据库或显示错误.

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.

我打算用嵌套的if语句执行30 if语句:

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;
    }   
}

但是我在使用$ q引用变量/字段名称时遇到错误.应该是[$ q]还是其他?

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.

谢谢

推荐答案

使用此:

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

在您自己的代码中,您有多余的'

In your own code you had weird extra '

这篇关于使用动态命名循环遍历多个POST变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆