2

I'm guessing this has been asked before, but I did some searching and haven't been able to find an answer (probably because of my lack of terminology).

I'm working on an application that displays a bunch of rows of inputs in a table and when the form is submitted I need to iterate over every input updating the database with the input's value. What I've been doing is naming inputs like this:

<input type="text" name="name1"><input type="text" name="gender1"> ...
<input type="text" name="name2"><input type="text" name="gender2"> ...
<input type="text" name="name3"><input type="text" name="gender3"> ...
.
.
.

Then in PHP doing this:

for($i = 1; isset($_POST['name' . $i]); $i++)
{
    $name = $_POST['name' . $i];
    $gender = $_POST['gender' . $i];
    // update DB with input values
}

In my application rows can be added and deleted, there are about 6 inputs in each row, and often dozens of rows. This just seems kind of messy to me and I'm wondering if there is a better/cleaner way of doing it?

4

1 回答 1

10

最好通过以下方式使用HTML input array

<input type="text" name="name[]">
<input type="text" name="gender[]">

在 PHP 中,您必须执行以下操作

$cnt = count($_POST['name']);
for($i=0;$i<$cnt;$i++){
   echo $_POST['name'][$i];
   echo $_POST['gender'][$i];
   ....
   // do any update with database
}
于 2012-12-02T17:36:43.570 回答