0

I have a stack of 'Select' menus / dropdowns on a PHP form on my website.

I'd like to check an option on each menu has been selected before processing the rest of the form, and wondered if I could loop through all of the fields with PHP?

Started with something like the following, but got a bit lost:

        foreach($_POST as $key => $val){
        //$errormsg.= $key." - ".$val."\n";

             if ($_POST['FIELD_NAME_HERE']){            
                     $FIELD_NAME_HERE_field = $_POST['FIELD_NAME_HERE'];
             } else {
                     $errormsg.= "<li>Please select from the FIELD_NAME_HERE options</li>";
             }

        }

Is this possible? And if so, how do I achieve this?

Thank you.

1 Answer 1

1

I think this might work for you:

foreach($_POST as $key => $val)
{
//$errormsg.= $key." - ".$val."\n";

    if ($val)
    {            
        ${$key.'_field'} = $val;
    } 
    else 
    {
        $errormsg.= "<li>Please select from the $key options</li>";
    }
}

It's probably not how I would have approached handling form errors though.

Sign up to request clarification or add additional context in comments.

5 Comments

It seems this ${$key}_field = $val; bit is giving me an error.
Out of interest, how would you handle it different to mine? Totally open to ideas here. Thanks again :-)
Wooooooooooop!!! It works :-D Guess I wasn't too far off then. Many thanks Fluffeh!!!!
@mcgarriers Okay, try that syntax - it's not giving me any errors in either eclipse or when I run the code (not testing it with post data though). I would be focusing on doing all the verification that I could before the form was submitted - then checking each one individually - and if needed outputting a seperate error message for each problem. Having said that, I have never had to use a form with loads of individual elements.
I've got some jQuery processing the form but this is a really good fallback should the JS fail/user disabled JS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.