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

╄→尐↘猪︶ㄣ 提交于 2020-01-02 18:52:31

问题


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


回答1:


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




回答2:


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



回答3:


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.




回答4:


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.




回答5:


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>';
}


来源:https://stackoverflow.com/questions/4225644/php-using-post-when-mutliple-form-fields-share-same-name-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!