views:

30

answers:

2

Hi experts, please help me with a simple PHP doubt.

I have a simple form:

< form action="foo" >
< label >Person:< /label >
< input type="text" id="name" >
< input type="text" id="last_name" >
< a href="javascript:addmore();">Add More

< /form >

Every time the user clicks Add More two new input fields will be dynamically created using jQuery. This can be done several times in a same form.

< form action="foo" >
< label>Person:< /label >
< input type="text" id="name" >
< input type="text" id="last_name" >

< input type="text" id="name_2" >
< input type="text" id="last_name_2" >

< a href="javascript:addmore();">Add More
< input type="sbumit" >
< /form >

Each pair (name and last_name) should create on record in my db.

Two Questions:
1) What is the best option for input id? Appending a counter is the best option?
2) How can I handle it in the backend using php?

Let me know if you need more info.

Thanks in advance.

A: 

This is a tipical scenario where you must use AJAX... there are several tutorials that will teach you how to use AJAX with JQuery. With regards to your question...

1) What is the best option for input id? Appending a counter is the best option? I think you best choice is to first create the element in the db using ajax and retrive the ID of the record that was created. Then, once you use that ID to identify the element in the HTML view.

2) How can I handle it in the backend using php? http://www.google.com/search?q=tutorial+jquery+ajax+php

Cristian
Ok. Maybe i was not clear on my request, the user will submit only once..but they might have one pair (name / last_name) or 20 pairs. How can I handle this in the php side?
Fernando
+3  A: 

Some code got lost in your post. And your form needs a method, probably POST.

Still, the best option would be creating inputs with the same name ending with []:

<input type="text" name="firstname[]" value="Fred" />
<input type="text" name="firstname[]" value="John" />

PHP will see it as an array with such elements:

<?php
$_POST['firstname'][0] // Fred
$_POST['firstname'][1] // John
?>

That is if you submit the form once for all the records. If you want to immediately save every record, google for ajax tutorials.

andr
thanks andr. I will try yours.. I will try to add a loop using the size of firstname to loop through all values$_POST['firstname'][i]
Fernando
solved. Thanks.
Fernando