开发者

PHP: using post when mutliple form fields share same name & id

开发者 https://www.devze.com 2023-01-26 03:01 出处:网络
That title probably doesn\'t mean much but what I have is a form that is generated dynamically. I hooks into a table of products, pulls out there name. I then create a form that displays the product w

That title probably doesn't mean much but what I have is a form that is generated dynamically. I hooks into a table of products, pulls out there name. I then create a form that displays the product with a checkbox and textbox next to it.

<form id="twitter-feed" name="twitter-feed" action="<?php echo $this->getUrl('tweet/') ?>index/tweet" method="post">
<table><tr>
<?php

$model = Mage::getModel("optimise_twitterfeed/twitterfeed");

$products = $model->getProducts();

foreach ($products as $product){
    echo '<tr>';
        echo '<td>';
 开发者_开发知识库           echo '<label for="'. $product .'">' . $product . '</label>';
            echo '<br /><input type="text" class="hashtag" name="tags" id="tags" value="#enter, #product, #hastag"';
        echo '</td>';
        echo '<td><input type="checkbox" name="chk" id="'. $product .'"></td>';
   echo '</tr>';
}
?>

<tr><td colspan="2"><input type="submit" name="submit" value="tweet"></td></tr>
</table>
</form>

As you can see there are checkboxes and textfields for each record. When I examine the $_POST data from the form it only retains fields for the last record.

Is there a way to pass all this data back to the action?

Cheers,

Jonesy


Use name="chk[]", then PHP will create an array for you.


Change your name arrtibutes to have an opening and closing square brace like this:

name="tags"
name="chk"

to

name="tags[]"
name="chk[]"

This will turn an array like:

$_POST['tags'][0] = VALUE
$_POST['tags'][1] = VALUE

$_POST['chk'][0] = VALUE
$_POST['chk'][1] = VALUE


Yes you can, set brackets at the end of the name value. E.g.:

<input type="checkbox" name="chk[]" id="'. $product .'">

Then you get an array as result in $_POST['chk']. Besides that, ids should always be unique. You can give same names, but you should always use different ids.


All of your fields have the same name, when that happens on any form you end up only seeing the last value because it's overwritten by the other fields.

Instead of <input type="checkbox" name="chk" id="124123"> do something like <input type="checkbox" name="chk[124123]" value='1'>

In your code you'd receive $_POST['chk'] as an array of values, only those values that were checked.


you can use as i have given example below. where i have taken one new variable $i = 0; and then you can use this $i into the foreach loop for displaying all product one-by-one.. i think this may help you.

$i = 0;
foreach ($products as $product){
 echo '<td><input type="checkbox" name="chk" id="'. $product[$i] .'"></td>';
}
0

精彩评论

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