在PHP中访问HTML表数据


Accessing HTML table data in PHP

我从SQL Select语句生成一个表,但也在每行上添加一个复选框,以便可以选择行,但我不知道如何在生成的表的每行中循环以查看该框是否被选中。

这可能吗?

我知道如何创建表,填充它,以及如何检查按钮,但我不知道如何访问每行按钮所在的单元格。

我不能单独创建每个复选框,因为它们是在循环通过SQL SELECT 中的行时与表一起创建的

如果要使用单选按钮,请在名称后添加[],将输入与数组链接在一起。即<input type="radio" name="foo[]" />然后,您可以使用foreach循环访问阵列。

如果要使用复选框,请为它们指定相同的名称,并在数组中使用[],每个名称都具有不同的value属性。即<input type="checkbox" name="foo" value="1" />您可以使用foreach循环访问这些值。

(在这两种情况下,您都需要在每个单选按钮之前的隐藏输入中有一个默认值。否则,您的数组将无法使用,因为php只读取选定的单选按钮。)

首先,我承认这不是最好的方法,但它会解决你的问题。

其次,我建议您将HTMLInput元素更改为type="checkbox"。为了能够知道哪些被检查了,你需要调整你的代码,使其看起来像下面这样:

<!-- HTML part -->
<form action="" method="post">
    <!-- we need the form as the parent to the table so content can be posted to the server -->
    <table ....>
        <thead>
            <tr>
                <th>&nbsp</th> <!-- we'll put our checkboxes in this column of the table -->
                ...
            </tr>
        </thead>
        <tbody>
            <?php
                foreach ($rows as $row) {
            ?>
            <tr>
                <td><input type="checkbox" name="chkSelect[]" value="<?php echo $row['id']; ?>" /></td>
                ....
            </tr>
            <?php
                }
            ?>
        </tbody>
    </table>
    <button type="submit" name="btnDelete" value="">Delete</button> <!-- This is assuming we're trying to delete the selected items -->
</form>
<!-- HTML end -->

在这一点上,我们已经准备好了我们的形式;注意,复选框名称后面有[],这允许在PHP端将其作为数组进行处理。在PHP方面,您只需要进行正常的表单处理,如下所示:

if (filter_has_var(INPUT_POST, 'btnDelete')) {
    $checkedIds = filter_input(INPUT_POST, 'chkSelect', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    // if we loop through the array, we can see the selected item ids
    var_dump($checkedIds);
}