0

I am trying to post the value post the value of the checkboxes to my database. If all the checkboxes are selected the checkboxes are sending the value 1 to the database. But when a checkbox is not selected the post dont works.

On the PHP page that post the data to the database I get Notice: Undefined index for the checkboxes that are not selected. Witch means that the not selected textboxes are sending an empty post.

Is there a way to fix this? Can I define a value for the not selected textboxes?

Here are my textboxes:

<input type="checkbox" name="psv1" id="psv1" value="1" class="flat" />
<input type="checkbox" name="psv2" id="psv2" value="1" class="flat" />
<input type="checkbox" name="psv3" id="psv3" value="1" class="flat" />
<input type="checkbox" name="psv4" id="psv4" value="1" class="flat" />
<input type="checkbox" name="psv5" id="psv5" value="1" class="flat" />

As you see, the textboxes are posting the value 1 when they are selected.

I am trying to get the value of the textboxes with the following in the PHP script:

$psv1 = $_POST['psv1'] ;
$psv2 = $_POST['psv2'] ;
$psv3 = $_POST['psv3'] ;
$psv4 = $_POST['psv4'] ;
$psv5 = $_POST['psv5'] ;

I get the Notice: Undefined index for variables that are not selected.

John
  • 904
  • 8
  • 22
  • 56
  • 3
    unchecked checkboxes are not typically posted, this is the expected behaviour, use `$psv1 = isset( $_POST['psv1'] ) ? 1 : 0;` instead – ArtisticPhoenix Jul 13 '17 at 03:36

1 Answers1

3

Checkboxes are not submitted unless they are checked. What value are they when not checked where did you specify this. You didn't. The simplest way is to check if they are set and then set a default value.

$psv1 = isset( $_POST['psv1'] ) ? 1 : 0;

This ( Ternary form ) is a equivalent to

if(isset( $_POST['psv1'] ) ) {
   $psv1 = 1;
}else{
   $psv1 = 0;
}

It's just the short hand form, In PHP7 I think they have null coalescing operator which may make it even shorter syntax.

PHP ternary operator vs null coalescing operator

But as I mainly program in production code, we haven't moved to PHP7 yet, so I haven't delved to deeply into that.

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • @John - glad I could help, be sure to accept the answer for future users so they can see that it is "solved" in this case it's very simple and very common thing, I am sure has been covered before. But it's probably less work to answer then to even point you to another answer. – ArtisticPhoenix Jul 13 '17 at 03:48