PHP: working with checkboxes
I have a form, and inside it there's a while() with checkboxes.
I wish to have so when you mark and then press submit, the message will remove.
Now, I have the checkboxes, and the submit button and so. Now all my checkboxes are like this:
<input class="cbPick" name="cbPick" type="checkbox" value="<?php echo $id; ?>">
How can i work with that in PHP? Should i do, $_POST["cbPick"] to know if its marked or not ?
And when i have more with these, how can i know which开发者_运维知识库 is which?
Check boxes require the use of an array. PHP will automatically place the checked boxes into an array if you place [] brackets at the end of each name.
Please choose type of food:<br />
Steak:<input type="checkbox" value="Steak" name="food[]">:<br />
Pizza:<input type="checkbox" value="Pizza" name="food[]">:<br />
Chicken:<input type="checkbox" value="Chicken" name="food[]">:<br />
Then you can do
$foodArray=$_POST['food'];
echo $foodArray[0]; //Steak Value
echo $foodArray[1]; //Pizza Value
echo $foodArray[2]; //Chicken Value
PS - This information was found by Googling "Checkboxes PHP" and clicking the first link. I encourage you to do at least a little research in the future before posting a question that has anwers so readily available.
if (!empty($_POST['cbPick']])) {
// Do stuff here
}
empty() checks first for existence, then if the value is non-nullish (null, zero, empty string, etc). That way you won't get a notice if the array key doesn't exist. Checkboxes are a little weird in that they only come through in the $_POST array if they are checked. Otherwise the variable is not posted at all.
If you use the same name (cbPick[]
) for a few checkboxes, $_POST["cbPick"]
will be filled as an array with each of the checked values.
精彩评论