Reputation: 28354
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?
Upvotes: 2
Views: 4573
Reputation: 15981
Better to use following way by taking HTML input array
<input type="text" name="name[]">
<input type="text" name="gender[]">
In PHP, you have to do following
$cnt = count($_POST['name']);
for($i=0;$i<$cnt;$i++){
echo $_POST['name'][$i];
echo $_POST['gender'][$i];
....
// do any update with database
}
Upvotes: 10