简体   繁体   English

PHP计算html表单中的POST元素

[英]PHP count POST elements from html form

I have a html form which I am sending to a php form. 我有一个HTML表单,正在发送到php表单。 I am able to set everything to a variable just fine except for one field which can have 1-20 elemnts in it. 我可以将所有内容设置为一个变量,除了一个字段可以包含1-20个元素之外。 the name of what I am trying to POST is cred_x_name The problem is the user can put in 1 element or 20, and I am not sure how many are put in. I know I have to use the count function, but don't know how to use it. 我要发布的内容的名称是cred_x_name问题是用户可以放入1个元素或20个元素,并且我不确定要放入多少个元素。我知道我必须使用count函数,但是不知道如何使用它。 So far I have 到目前为止,我有

$j=  count($cred_req_name);
for ($i=0; $i<$j;$j++)
{
echo "test";
}

Not sure if this is the right approach. 不知道这是否是正确的方法。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks, Ravi 谢谢,拉维

Having taken a look at your link, I think I would do something like the following: 看完您的链接后,我想我会做以下事情:

$credentials = array();

for ($i = 1; $i <= 20; $i++)
{
    if (isset($_POST['cred_'.$i.'_name']) && !empty($_POST['cred_'.$i.'_name'])
    {
        $credentials[] = array(
            'name' => $_POST['cred_'.$i.'_name'],
            'city' => $_POST['cred_'.$i.'_city'],
            //  etc
        )
    }
}

Then what you have is a full array of all the credentials entered by the user, and empty lines will be ignored. 然后,您拥有的是用户输入的所有凭据的完整数组,并且空行将被忽略。 For instances if only 3 credentials were entered, then your array $credentials will be 3 elements long. 例如,如果仅输入3个凭据,则$credentials数组的长度为3个元素。 You can then use this array to process what you want, such as entering credentials in a database. 然后,您可以使用此数组来处理所需的内容,例如在数据库中输入凭据。 This time, you will use foreach to parse the array you just created. 这次,您将使用foreach解析刚创建的数组。

Beware of capitalization too: 'cred_'.$i.'_name' is not the same thing as 'Cred_'.$i.'_name' . 也要注意大写: 'cred_'.$i.'_name''Cred_'.$i.'_name'是不同的东西。 Turn all your "name" attributes into "cred_x_foo" (instead of "Cred_x_foo") otherwise things won't work as expected. 将所有“名称”属性都转换为“ cred_x_foo”(而不是“ Cred_x_foo”),否则事情将无法按预期进行。

Anyway, don't forget to sanitize your inputs cause they don't seem to be as of now. 无论如何,不​​要忘记清理您的输入内容,因为到目前为止它们似乎还不是。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM