开发者

PHP loop through array of HTML textboxes

I have an HTML form with a dynamic number of checkbox fields, all of which are encapsulated within a submit form. When the form is submitted, I want to l开发者_如何学JAVAoop through the values of each checkbox field with a PHP script. At the same time, I have to keep a certain ID associated with the checkbox field so that when I loop through each one in my script, I can use the ID to update the correct row in my database. Currently, I have:

<input checked="checked" name="attended_<?php echo($pid); ?>"

I'm just not sure how to go ahead and access all of the attended[] values from my PHP script (and keep the ID at the same time). Would I use a multidimensional array like the following?

<input checked="checked" name="attended[<?php echo($i); ?>][<?php echo($pid); ?>]; ?>"

I'd appreciate any help on this. Thanks!


lets say this is data from form

<input checked="checked" name="attended[1]; ?>"
<input checked="checked" name="attended[2]; ?>"

<input checked="checked" name="attended[3]; ?>"
<input checked="checked" name="attended[4]; ?>"

<input checked="checked" name="hello[1]; ?>"
<input checked="checked" name="hello[2]; ?>"

this is how it would look as array. not needed its just for show

// $k        =>      $v
$attended[1]='blah blah';
$attended[2]='blah blah';
$attended[3]='blah blah';
$attended[4]='blah blah';

$hello[1]='blah blah';
$hello[2]='blah blah';

science bit

foreach($attended as $k=>$v){

$sql = "UPDATE mytable SET attended = '$v', hello = '{$hello[$k]}' where id = '$k'";
$query = mysql_query($sql) or die("Cannot query the database.<br />" . mysql_error());

}

all associated data should have same pid e.g

<input checked="checked" name="attended[1]; ?>"
<input checked="checked" name="hello[1]; ?>"


Usually when I create checkboxes I put an index in the name. This way you can loop through each checkbox in your submittion code.

<input type="checkbox" name="cbGroup[1]" value="y" />
<input type="checkbox" name="cbGroup[2]" value="y" />
<input type="checkbox" name="cbGroup[3]" value="y" />

and in your PHP

foreach($_POST['cbGroup'] as $index=>$checkbox) {}

You'll want to make sure your $_POST['cbGroup'] is set though because it won't be if the checkbox isn't checked.

Edit: Sorry, I should learn to read the question fully heh :) I use multidimensional arrays in PHP with HTML inputs all the time and I think it's the way I would go.


Maybe you could do it with a hidden field which is sort of 'associated' with the checkbox by the name:

<input checked="checked" name="attended_<?php echo($i); ?>"
<input type="hidden" name="attended_<?php echo($i); ?>_reference" value="<?php echo($pid); ?>" />

So while processing the POST-data after a submit, you could put the references together again with some string-manipulation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜