我有一个动态表,它设置在foreach中,因此为获取的数组的每个项创建一个新行。我在最后一列中每行都有一个按钮。当点击提交按钮时,我会收到PHP中的id。提交操作是正确的,但我在PHP中收到了错误的id。它基本上是在提交时获取数组的最后一个id。知道为什么吗?
这是表格:
<form method="post" id="frm-example" action="<?php echo $_SERVER["PHP_SELF"] . '?' . e(http_build_query($_GET)); ?>">
<table id="example" class="display compact">
<thead>
<th>Device</th>
<th>Sales date</th>
<th>Client comments</th>
<th>Breakage count</th>
</thead>
<tbody>
<?php foreach ($arr_cases_devices as $cases) { ?>
<tr>
<td>
<?php echo $cases['name']; ?>
</td>
<td>
<?php echo $cases["sales_date"]; ?>
</td>
<td>
<?php echo $cases["dev_comment"]; ?>
</td>
<td>
<input type="hidden" name="device_id_breakage" value="<?php echo $cases["Dev_Id"]; ?>" />
<button type="submit" name="see_rma">See RMA</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
当点击see_rma
时,这是我在PHP中收到的:
if (isset($_POST['see_rma'])) {
$selected_dev = e($_POST['device_id_breakage']);
print_r($selected_dev); // prints the "Dev_Id" of the last row, not of the row clicked
}
如果我尝试在表的循环内打印$cases["Dev_Id"];
,它打印得非常好,所以它正确地打印了每行的Dev_Id。因此,这意味着数组或数据没有任何问题。我不知道为什么会发生这种情况,但这肯定是我第一次遇到这种问题。
我在许多其他表格中都这样做,但由于某些原因,在这张表格中无法正常工作。
您的表单中有多个名称相同的<input>
元素,所有这些元素都将在提交表单时提交,但PHP只能获得其中一个。这就是为什么你最终只得到$_POST
中的最后一个。
看起来你应该能够通过将一些属性从隐藏的输入移动到按钮中(替换隐藏的输入(来解决这个问题。
<button type="submit" name="device_id_breakage" value="<?php echo $cases["Dev_Id"]; ?>">
See RMA
</button>
只有单击的按钮才会被提交。请注意,更改按钮名称后,$_POST
中将不再有see_rma
,因此,如果您有任何依赖于此的代码,则需要更改它以查找其他名称。