MySQL Forums
Forum List  »  PHP

Re: Referencing Checkbox Form Values passed to a PHP form handler script
Posted by: Mark Timmick
Date: March 09, 2006 12:23AM

Using $_POST vs. $_REQUEST worked. Thanks so much Peter.

As far as using two form vars with the same name, HTML forms appearently only send values for checkboxes that are "checked". I was having problems knowing which ones were sent to the php form handler. I found the following advice on another web site that forces values to be passed to the action script for all checkboxes, whether they were checked or not. As you'll see, the author acknowledges there may be problems with this approach. I would have tried his other recommended approach but frankly I didn't udnerstand it. What do you think??

ARTICLE: Working with Checkboxes in PHP
by John Coggeshall
03/13/2003
Source: OnLamp.com PHP DEVCENTER

Due to the nature of checkboxes, you may have already realized that checkboxes will not show up in PHP unless they have been checked. Dealing with this circumstance can be annoying (and perhaps insecure) unless properly dealt with. The first of these methods basically involves creating a hidden form element with the same name as the checkbox element and setting its value to zero, as shown below:

<input type="hidden" name="mycheckbox" value="0">
<input type="checkbox" name="mycheckbox" value="1">

The idea behind this solution is based on how PHP will respond if two elements (using the same method) have the same name. As was the case with the <select> element when in multi-select mode, PHP uses the last value provided to it. The hidden element will be used because the checkbox element is not sent to PHP if it is unchecked. Likewise, if the checkbox element is checked when the form is submitted, its value will override that of the hidden element.

Unfortunately, the drawback to this solution is a complete reliance on the browser to always send the hidden element before the checkbox element. Although it is logical to assume that elements will be sent in the same order as they are presented in the HTML document, there is no guarantee that this situation will be the case.

The second solution to this problem is much more eloquent for most situations. Unless you are unsure if a given checkbox was displayed to the user (if it may or may not be present in the form, depending the logic that created the form) create a boolean value based on the existence of the checkbox:

<?php
/* Assume a checkbox by the name 'mycheckbox' exists */
$checkbox = ($_GET['mycheckbox'] == 1);
?>

The value of the $checkbox boolean will be set to true if the mycheckbox element exists (with the proper value), and false otherwise.

Options: ReplyQuote




Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.