开发者

PHP: saving multiple tuples to the same table

I am trying to save data into the same table several t开发者_运维技巧imes from the same $_POST array. You see, on my registration form a family is allowed to specify the names, gender and age of all members they wish to bring along.

This data is being stored in a database table called aditional_member. Based on family size, I am dynamically generating html table rows where each row has the number of input fields required.

<tr id="additionalmember_3">
    <td><input type="text" name="first_name1" maxlength="50" value="" /></td>
    <td><input type="text" name="last_name1" maxlength="50" value="" /></td>
    td><select name="gender1" value="" ><option value='Male'>Male</option><option value='Female'>Female</option></select></td>
    <td><select name="age_group"value="" ><option value='18 to 30'>18 to 30</option><option value='31 to 60'>31 to 60</option></select></td>      
</tr>

When I POST, let us say I have three sets of input(3 table rows as above), Is there a simple way to insert into the addional_member table the data from row one, then row two, and so on. I tried looping the insert statement, which failed. I am basically open to suggestions, I do not need to use a table.

Any ideas, Thank you.


Changing the name of the inputs to have [] at the end will cause PHP to treat the $_POST elements as an array. Just iterate over the indexes and pull from each array together.


I don't know if I understood correctly what you want, but try this

    <?php
    //having 3 rows to insert 
    for($i=1;$i<4;$i++){

        mysql_query("INSERT INTO Table (field1, field2, field3) values (
          '".$_POST['first_name'.$i]."',
          '".$_POST['last_name'.$i]."',
          '".$_POST['gender'.$i]."')");
    }
?>


Use the "[]" feature of PHP to pass your post documents an array, so your rows will look like this:

<tr>
    <td><input type="text" name="first_name[]" maxlength="50" value="" /></td>
    <td><input type="text" name="last_name[]" maxlength="50" value="" /></td>
    <td><select name="gender[]" value="" >
           <option value='Male'>Male</option>
           <option value='Female'>Female</option>
        </select>
    </td>
    <td><select name="age_group[]" value="" >
           <option value='18 to 30'>18 to 30</option>
           <option value='31 to 60'>31 to 60</option>
        </select>
    </td>      
</tr>

When you get the submitted data, just use print_r() to dump it to the screen and you'll see how it's organized for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜