Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple php question 3

Status
Not open for further replies.

btween

Programmer
Aug 7, 2003
338
US
If I have a form with 5 checkboxes. They can all have the same label or different labels. For every checkbox that is checked, when the form is submitted the next page should display the total number of checkboxes checked.

in other words if the user checks 3 boxes i need the next page to display: your score is 3.

 
if the checkboxes all have the same name, they are passed to the php page as an array. therefore, use the count() function to display the number of elements within the array.



*cLFlaVA
----------------------------
[tt]"quote goes here"[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
 
Code:
<?
if (isset($_POST['cbox'])){
echo "Your score is ". count($_POST['cbox']);
echo "<br/><br/>";
}
?>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
One&nbsp;<input type="checkbox" name="cbox[]"/><br/>
Two&nbsp;<input type="checkbox" name="cbox[]"/><br/>
Three&nbsp;<input type="checkbox" name="cbox[]"/><br/>
Four&nbsp;<input type="checkbox" name="cbox[]"/><br/>
Five&nbsp;<input type="checkbox" name="cbox[]"/><br/>
<input type="submit" name="submit" value="submit" />
</form>
 
if the checkboxes all have the same name, they are passed to the php page as an array.

sfaik this is only true if the name ends with "[]". Otherwise php will only be able to address the last form control with that name in a form.
 
if you don't want them to all have the same name, as in that array suggestion as above, you could name them all with a pattern so they are similar, like this:

Code:
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
One&nbsp;<input type="checkbox" name="cbox_one"/><br/>
Two&nbsp;<input type="checkbox" name="cbox_blah"/><br/>
Three&nbsp;<input type="checkbox" name="cbox_whatever"/><br/>
Four&nbsp;<input type="checkbox" name="cbox_wow"/><br/>
Five&nbsp;<input type="checkbox" name="cbox_ok"/><br/>
<input type="submit" name="submit" value="submit" />
</form>

then your processing code could simply go through all the variables in the $_POST array and see which ones are the checkboxes (ie, they match with starting "cbox_", or ending..., or whatever pattern you use for the checkbox names) and just count how many there are. checkboxes which are not checked will not be in the post array, therefore the count will be accurate to what you want.

Code:
$count = 0;
foreach ($_POST as $name => $val) {
   if (strpos($name,"cbox_") !== false) $count++;
}
echo "Your score is: $count";
 
Hey guys, it doesn't matter if the checkboxes have the same name or no, but what i need is for the checkbox to remain checked even after the page reloads with the score.

how could I do this with jpadie's solution?

 
almost impossible with jpadie's solution... because it will condense down into a numerically dense array, meaning there will be no way to know "which" one it was...

the best way would be to have my solution, which has a unique name for each one (a pattern like "cbox_" followed by a unique name, including possibly just a unique number like the ID from the database or whatever).

then, when you are re-drawing the page, on each input check box, you put an if statement to see if that same name'd checkbox was in the POST to the page, and if so, add the "CHECKED" tag to the HTML for that checkbox... something like this:

Code:
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
One&nbsp;<input type="checkbox" name="cbox_1001"<?=((isset($_POST["cbox_1001"]))?" CHECKED":"")?>/><br/>

Two&nbsp;<input type="checkbox" name="cbox_1002""<?=((isset($_POST["cbox_1002"]))?" CHECKED":"")?>/><br/>

Three&nbsp;<input type="checkbox" name="cbox_1003""<?=((isset($_POST["cbox_1003"]))?" CHECKED":"")?>/><br/>

Four&nbsp;<input type="checkbox" name="cbox_1004""<?=((isset($_POST["cbox_1004"]))?" CHECKED":"")?>/><br/>

Five&nbsp;<input type="checkbox" name="cbox_1005""<?=((isset($_POST["cbox_1005"]))?" CHECKED":"")?>/><br/>

<input type="submit" name="submit" value="submit" />
</form>
 
shadedecho,

your presumption is not correct if the OP is dynamically generating the checboxes. if this is the case, he/she can simply loop through when creating HTML (as normal) and simultaneously check that index within the POSTed array. if it's checked, write the appropriate html (checked="checked").



*cLFlaVA
----------------------------
[tt]"quote goes here"[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
 
cflava,

I'm not sure exactly how to do this. I know in javascript you can use the "in position" syntax ( [2] would be the third checkbox populated on the page) to pick the item from the array but how can you do this with php ?

 
I'm using padie's code:

Code:
<?
if (isset($_POST['cbox'])){
echo "Your score is ". count($_POST['cbox']);
echo "<br/><br/>";
}
?>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
One&nbsp;<input type="checkbox" name="cbox[]"/><br/>
Two&nbsp;<input type="checkbox" name="cbox[]"/><br/>
Three&nbsp;<input type="checkbox" name="cbox[]"/><br/>
Four&nbsp;<input type="checkbox" name="cbox[]"/><br/>
Five&nbsp;<input type="checkbox" name="cbox[]"/><br/>
<input type="submit" name="submit" value="submit" />
</form>

 
I used shadedecho's solution. It worked fine. the only reason why I wanted to go with cflava's suggestion was out of curiosity.

 
@btween

it's easy enough to do what you want with dynamic forms or static forms (a variation on shadecho's theme). however with the static variant you have to hard code the code in each input which adds to the effort.

here is some code that exemplifies how to generate the form dynamically from a spoofed database and keeps the options "sticky".

Code:
<?
//spoof some data
//nowmally this would come from a database

$array = array(
			array("id"=>0,"fruit"=>"apple"), 
			array("id"=>1,"fruit"=>"banana"), 
			array("id"=>2,"fruit"=>"coconut"), 
			array("id"=>3,"fruit"=>"damson"), 
			array("id"=>4,"fruit"=>"elderberry")
		);

//generate the checkboxes
$cbox = "";
foreach ($array  as $box){
	$checked = (isset($_POST['cbox']) && in_array($box['id'],$_POST['cbox'])) ? 'checked="checked"' : "";
	$cbox .= "<input type=\"checkbox\" name=\"cbox[]\" value=\"{$box['id']}\" $checked /> &nbsp; {$box['fruit']} <br/>";
}
//calculate the "score"

$score = 	isset($_POST['cbox'])
			?  "Your score is ". count($_POST['cbox']) ."<br/>" 
			: 	"";


//display the form


echo <<<EOL
$score
<form method="post" action="{$_SERVER['PHP_SELF']}">
<fieldset style="width:15%;">
$cbox
<input type="submit" name="submit" value="submit" />
</fieldset>
</form>
EOL;
?>
 
cLFlaVA-
jpadie's solution calls for relying on PHP to add all the identically named checkboxes that were submitted to it to an array. sounds nice that PHP does this magic for you, but...

if you have 5 checkboxes on the original page, and you check only the first, third, and fifth box (leaving #2 and #4 empty) and click submit, PHP will create an array in the POST array that only has 3 elements in it, indexed 0, 1, and 2. That was fine for the original question, which was simply to count ("score") the number of submitted checkboxes, done via the length of that auto-created array.

However, now, when re-drawing the page again, it needs to know exactly which checkboxes to re-check. But as I showed, you cannot rely on the position/index in the PHP array of submitted checkboxes to tell you the correct checkbox to then add the "CHECKED" tag to, because it will not keep the index from the original page, but will index based upon only the submitted boxes.

To illustrate:
say you check box 2 and box 5. In the redrawing of the page, how would you know that the $_POST["checkbox"][0] actually refers not to box 1 but box 2, and that $_POST["checkbox"][1] actually corresponds to the 5th checkbox, not the second? See?

You can't. there's nothing you can rely on in the numerical auto-indexing that will give you a clue to which unique box the check came from.

So, if you need to be able to know which box it was... you have to give each checkbox a unique name/id. At least with my way, by creating a name pattern to them, you can easily pick them out of the $_POST array in a foreach loop.
 
shadedecho: have you checked the posting above this? i thought i had showed that you could do what the user asked. of course, i did not use the array index for the reason you point out, but there are plenty of ways to skin a cat.

I typically DO name checkboxes using the unique id of the row that generates them. but for smaller datasets (where in_array is not too much of an overhead) I also freely make use of the unfilled square brackets.
 
i've had experiences with some browsers/platforms in the past which do not pass values in checkboxes along, but instead the value you get for a submitted checkbox is simply "On", similar to how things seemed to work when I did stuff in ASP years ago.

Yes, knowing the value of the checkbox DOES solve the problem, as long as you can assume you'll always get the value. BUT, since I had some gotchas with that once long ago, ever since, I've always relied on the name/id only, and never used "value" in checkboxes. Perhaps my paranoia is just that, and purely an artifact of the past, but this is why my behavior defaults to the name/id-only approach even today. :)
 
@shadedecho

that would be useful knowledge for this forum. can you provide a list of those browsers that don't pass on the value of a checkbox? the name[] is a widely and often used construct and we'd all benefit from knowing which browsers to code exceptions for. maybe you could post the list as a FAQ as well as in this thread.

thanks.
 
Maybe I don't know what is the problem but wouldn't explicitly setting the indices on the elements solve the problem of knowing which checkbox was checked. It is simple, identifies the element and can be used with dynamically output html if need be:
Code:
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
One&nbsp;<input type="checkbox" name="cbox[0]"/><br/>
Two&nbsp;<input type="checkbox" name="cbox[1]"/><br/>
Three&nbsp;<input type="checkbox" name="cbox[2]"/><br/>
Four&nbsp;<input type="checkbox" name="cbox[3]"/><br/>
Five&nbsp;<input type="checkbox" name="cbox[4]"/><br/>
<input type="submit" name="submit" value="submit" />
</form>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top