Kostas
Kostas

Reputation: 1369

Multiple instances of same elements in a form

From the database, I load some data that user can edit.

Let's say we have this form:

<form>
Name: [TextBox]
Data: [TextArea]
-------------------
Name: [TextBox]
Data: [TextArea]
...
Name: [TextBox]
Data: [TextArea]
-------------------
[Submit Button]
</form>

What names should the elements have?

What is the best approach to fetch the posted data using PHP, so I can understand what's the id for each one?

Note: I want to have only 1 submit button!

Thanks...

Upvotes: 2

Views: 1599

Answers (1)

NickSoft
NickSoft

Reputation: 3335

With PHP you can use an array:

Name: <input type="text" name="name[]" value="">
Data: <textarea name="data[]"></textarea>
...
Name: <input type="text" name="name[]" value="">
Data: <textarea name="data[]"></textarea>

Then in PHP you can process it like this:

$nameArray = $_POST['name'];
$dataArray = $_POST['data'];
foreach($nameArray as $key => $name){
  $data = $dataArray[$key]);    
}

Another way is to use php to generate names. Make them look like this:

Name: <input type="text" name="name[0]" value="">
Data: <textarea name="data[0]"></textarea>
Name: <input type="text" name="name[1]" value="">
Data: <textarea name="data[1]"></textarea>
...
Name: <input type="text" name="name[10]" value="">
Data: <textarea name="data[10]"></textarea>

This way you can be sure that $_POST['name'][10] corresponds to $_POST['data'][10].

Upvotes: 7

Related Questions