我有一个这样的表格:
<?php if (isset($_POST['artist'])) {
// do something
} ?>
<form name="admin_on_artist_<?php echo $artist->ID; ?>" action="" method="POST">
<p class="artist-negative">
<label for="artist"><input type="checkbox" name="artist_<?php echo $artist->ID; ?>" id="artist_<?php echo $artist->ID; ?>"> Check this?</label>
</p>
<button type="submit">Update</button>
</form>
在相关页面上,此表单在foreach循环中多次显示。但是,当我提交任何给定的表单时,它会更新所有表单,这不是我想要的。
如何将$artist->ID
附加到$_POST['artist']
,以便我得到类似的内容:
$_POST['artist_1']
匹配复选框属性?
答案 0 :(得分:0)
您可以将生成前端表单标记的foreach
与处理表单提交的foreach
配对。类似的东西:
<?php
$regex = '/^artist_([0-9]+)$/'
foreach (array_keys($_POST) as $key) {
if (preg_match($regex,$key,$matches)) {
$artistId = (int)$matches[1];
// do something with $_POST[$key] according to $artistId
}
}
这适用于单个字段提交或多字段提交。
或者,您可以在JS
的前端执行某些操作(正如@smith在评论中所建议的那样),以确保表单提交始终具有相同的,众所周知的密钥,并使用当前提交填充隐藏的表单。使用此方法,您必须在包含ID的表单中添加另一个字段。
答案 1 :(得分:0)
对此的解决方案比起初我能够掌握的要简单得多,但基本上我只需要这样做,这与我原来的问题之间的关键区别在于前两行:
<?php $artist_form_id = 'artist_'.$artist->ID;
if (isset($_POST[$artist_form_id])) {
// do something
} ?>
<form name="admin_on_artist_<?php echo $artist->ID; ?>" action="" method="POST">
<p class="artist-negative">
<label for="artist"><input type="checkbox" name="artist_<?php echo $artist->ID; ?>" id="artist_<?php echo $artist->ID; ?>"> Check this?</label>
</p>
<button type="submit">Update</button>
</form>