Page 1 of 1

problem with checkboxes

Posted: Wed Jul 19, 2006 12:19 pm
by farid
:( Hi y'all!!

I suppose it is an easy question, i have the following

Code: Select all

<form id="form1" name="form1" method="post" action="2.php">
  <label>
  <input name="check1" type="checkbox" id="check1" value="1" />
  Opc1<br />
  </label>
  <label>
  <input name="check2" type="checkbox" id="check2" value="2" />
  </label> 
  Opc2
  <p>
    <label>
    <input type="submit" name="Submit" value="Submit" />
    </label>
</p>
</form>
And in the next page, 2.php, I have:

Code: Select all

<?php 
	  echo $_POST['check1'];
	  echo "<br>";
	  echo $_POST['check2'];
?>
And the problem is that if the checkboxes in the first page are not selected, which it may happen, it says: "Notice: Undefined index: check1 in D:\inetpub\InetGREGION9\php\fichas\Tests\2.php on line 9"

What can I do to solve this prob??
Thanks in advanced!! :D

Posted: Wed Jul 19, 2006 12:24 pm
by Burrito
look at isset() you should.

Posted: Wed Jul 19, 2006 12:28 pm
by Ollie Saunders
To define what you are experiencing:
User agents do not send any data from unchecked check boxes or radio boxes. So it is impossible to tell the difference between one that doesn't exist and one that does exist but hasn't been checked.

IMO this is a terrible feature of user agents.
This may be a good enough fix for your problem:

Code: Select all

if (isset($_POST['check1'])) {
    // you know that check1 was checked
} else {
    // you know that check1 was either not checked or never existed
}
most of the time it is safe to assume that it does exist by wrapping that in an !empty($_POST) condition:

Code: Select all

if (!empty($_POST)) {
    if (isset($_POST['check1'])) {
        // you know that check1 was checked
    } else {
        // you can be sure that check1 was left unchecked and did exist
    }
}
Of course you may not need those { blocks } in which case you can do this:

Code: Select all

if (!empty($_POST)) {
    $check1WasChecked = isset($_POST['check1']);
}

Posted: Wed Jul 19, 2006 12:29 pm
by farid
Great!! Thanks burrito!! :D

Posted: Wed Jul 19, 2006 12:41 pm
by Burrito
farid wrote:Great!! Thanks burrito!! :D
thank ole you should, provided a much better description than I he did.