我正在循环通过一堆数组类型字段。我有两个名称为"taxable[]"answers"ship[]"的复选框
我在mysql中输入这些复选框,并注意到表单中的其他字段都正确提交了。
如果我有6行复选框,我取消选中第一行。最后一行复选框会受到影响。
同样,如果取消前两行,最后两行也会受到影响。
我把它分解成下面简单的php ..在我的复选框中循环,我看到循环的最后一次迭代是复选框没有设置的地方,而不是第一次循环。知道这是怎么回事吗?我还检查了数组的大小,它与每种类型的字段数量相匹配。
echo sizeof($post["prodID"]);
for($i = 0; $i<sizeof($post["prodID"]); $i++){
echo $i.' taxable '.$post["taxable"][$i].' '.$i.' ship '.$post["ship"][$i].' <br />';
continue;
}
html for form:
<? foreach($products as $prod): ?>
<tr class="<?= $prod["activeText"] ?>">
<td><?= $prod["productid"] ?></td>
<td><input type="text" name="name[]" value="<?= $prod["itemname"] ?>"/></td>
<td><textarea name="description[]"><?= $prod["description"] ?></textarea></td>
<td><input type="text" name="cost[]" value="<?= $prod["cost"] ?>"/></td>
<td><input type="text" name="price[]" value="<?= $prod["price"] ?>"/></td>
<?php $checked = ($prod["taxable"] == 1) ? "checked='checked'" : ""; ?>
<td style="padding:0px;"><input style="position:relative; right:-10px;"type="checkbox" name="taxable[]" <?= $checked ?>/></td>
<td>
<select name="tax[]">
<?php foreach($taxes as $tax){
$selected = ($prod["inventoryTaxRateID"] == $tax["inventoryTaxRateID"]) ? 'selected="selected"' : '';
?>
<option <?= $selected ?> value="<?= $tax["inventoryTaxRateID"] ?>"><?= $tax["name"] ?></option>
<?php } ?>
</select>
</td>
<?php $ship = ($prod["ship"] == 1) ? 'checked' : '' ?>
<td><input type="checkbox" name="ship[]" <?= $ship ?> /></td>
<td><input type="text" name="sandh[]" value="<?= $prod["shipping_handling"] ?>"/></td>
<td><?= $prod["activeText"] ?></td>
<td>
<? if($prod["inactive"] !== null): ?>
<input type="button" name="changeStatus" value="<?= $prod["buttonText"] ?>" onclick="window.location='<?= base_url() ?>management/productManager/activate/<?= $prod["inventoryItemID"] ?>/<?= $prod["activeStatus"] ?>/<?= $category ?>'" />
<? endif; ?>
<input type="hidden" name="prodID[]" value="<?= $prod["inventoryItemID"] ?>" />
<input type="hidden" name="cat[]" value="<?= $prod["cat"] ?>" />
</td>
</tr>
<? endforeach; ?>
这是因为PHP只接收选中的复选框。未选中的复选框不会通过浏览器发送。示例
<input type="checkbox" name="ship[]" value="1" />
<input type="checkbox" name="ship[]" value="2" />
<input type="checkbox" name="ship[]" value="3" />
<input type="checkbox" name="ship[]" value="4" />
如果你选择了第一个和最后一个复选框,浏览器只会发送第一个和最后一个复选框。PHP将看到$_POST['ship']
为
Array(
[0] => 1
[1] => 4
)
您可以为输入名称添加索引,这可能会解决您的问题。
。
<input type="checkbox" name="ship[0]" value="ship1" />
<input type="checkbox" name="ship[1]" value="ship2" />
<input type="checkbox" name="ship[2]" value="ship3" />
<input type="checkbox" name="ship[3]" value="ship4" />
如果你选择船1和船3,$_POST['ship'][0]和$_POST['ship'][2]将被设置,而其他的将不在$_POST数组中,因为它们没有与表单一起提交。
你可以使用array_keys($_POST['ship'])
。
if(is_array($_POST['ship']))
{
foreach(array_keys($_POST['ship']) as $index)
{
echo $_POST['ship'][$index]."<br />";
}
}
返回所有选中的值