简体   繁体   中英

PHP count POST elements from html form

I have a html form which I am sending to a php form. I am able to set everything to a variable just fine except for one field which can have 1-20 elemnts in it. 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. 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. 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.

Beware of capitalization too: 'cred_'.$i.'_name' is not the same thing as 'Cred_'.$i.'_name' . Turn all your "name" attributes into "cred_x_foo" (instead of "Cred_x_foo") otherwise things won't work as expected.

Anyway, don't forget to sanitize your inputs cause they don't seem to be as of now.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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