|
Posted by Michael Fesser on 11/12/06 21:35
..oO(Amer Neely)
>I've got a dynamically built form with checkboxes for each element ( a
>list of file names in a directory). I need to grab only those checkboxes
>that are checked, so I can then delete those files.
Only checked checkboxes will be submitted by the browser.
>Does each checkbox name have to be unique?
No, you can use the same name, but different values. To make this work
in PHP you have to add brackets to the name, see below.
>I've tried:
> foreach ($_REQUEST as $field => $value)
> {
> echo "$field = $value<br>";
> }
>but that just grabs the last entry in the group.
>
>The line in question is:
><input type="checkbox" name="DeleteThis" value="<?php
>echo("$allfiles[$i]")?>"> <?php echo("$allfiles[$i]")?><br>
Some things:
1) You should not use $_REQUEST. This array contains data from different
sources, so you don't know where all the values actually came from. Use
the array that corresponds with the used method in your form, which
should be $_POST in this case.
2) Instead of $allfiles[$i] you can just use the variable $i as the
value of your checkboxes, that's enough. When processing the form use
that value to lookup the filenames in your $allfiles array.
3) To process multiple form controls that share the same name you have
to add square brackets to their name, e.g. "DeleteThis[]". This causes
PHP to store all the values in an array instead of a scalar.
So the code could look something like this:
if (isset($_POST['DeleteThis')) {
foreach ($_POST['DeleteThis'] as $index) {
if (isset($allfiles[$index])) {
// perform action to delete the file
}
}
}
The code for the checkboxes like I would probably write it:
printf("<label><index type='checkbox' name='DeleteThis[]'
value='%u'> %s</label><br>\n", $i, $allfiles[$i]);
HTH
Micha
Navigation:
[Reply to this message]
|