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?

1 Answer 1

9

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is the standard way to perform this task.
Can I be sure that different inputs in the same row will have the same indexes? (i.e. in my example the name and gender would need to have the same indexes if they were in arrays so that I would know to put them in the same row).
Yes, same row will have same indexes that is 100% sure
How would you apply jquery on these elements?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.