problem with checkboxes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
farid
Forum Commoner
Posts: 54
Joined: Thu Nov 11, 2004 4:20 pm
Location: Mexico

problem with checkboxes

Post 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
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

look at isset() you should.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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']);
}
User avatar
farid
Forum Commoner
Posts: 54
Joined: Thu Nov 11, 2004 4:20 pm
Location: Mexico

Post by farid »

Great!! Thanks burrito!! :D
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

farid wrote:Great!! Thanks burrito!! :D
thank ole you should, provided a much better description than I he did.
Post Reply