Post Data Handling


#1

I have a check box field with 5 choices.

Let's say the user checks 3 choices.

When I read the values of the choices using $_POST the checked items come across from the form fine but the unchecked boxes send nothing.

So I get an error in the Form Action code that is trying to read the output of all 5 check boxes.

How do I deal with this?

Mike Smith


#2

It is difficult to tell without seeing your code, but isset() should help, I think.


#3

This is normal behaviour.

You could use isset Eg.

if(isset($_POST['choice1'])) { $choice1 = true ;}
else{ $choice1 = false ;}

#4

As far as I know, unchecked checkboxes do not send anything through the $_POST variable, just the checked ones.


#5

Yes, this came up on another thread only a day or two ago.


#6

Thanks so much for this.

It worked perfectly.

Mike Smith


#7

Of course the values you assign don't have to be a boolean like the example, it could be anything, like 'yes' and 'no' or whatever you want the result to be. Or perform some action/function depending on it being set.

If there is a whole load of checkboxes, you may automate it with an array of the input names:-

$checkboxes = array('firstbox', 'secondbox', 'anotherbox', 'onemorebox'); // Names of inputs

foreach($checkboxes as $checkbox){   // Check them all
     if(isset($_POST[$checkbox])){ $boxresults[$checkbox] = true ;}
     else{ $boxresults[$checkbox] = false ;}
}

#8

While it is true that isset is the correct approach, your particular example is not for actual use.

The if statement already does a Boolean true/false check by default, therefore further specifying true/false is redundant and not necessary.


#9

Yes, maybe a bad example, but showing that values could be assigned.
So for a boolean, something more like.

$boxresult[$checkbox] = isset($_POST[$checkbox]);

#10

For clarification, my response was to post #3.