Inserting data from indefinite number of fields into MySQL
Posted: Wed Mar 18, 2009 11:48 am
For this app, users are able to create a "bundle" and add as many items as they'd like to the bundle.
Here's how it works:
The user enters the bundle title and description, and can then add items below. For each item, there is a row of six fields. See screenshot. Using jQuery, I've made it so that the user can dynamically add additional rows of fields (limited to 50). Each field's name auto-increments according to its row (e.g. item_name1 for row 1, item_name2 for row 2).
When the form is submitted, PHP inserts the bundle (just the title and description, not the individual items) into the Bundles table and retrieves the newly created bundle's ID. The individual items will be stored in the Bundle_Items table, and will be associated with their parent bundle by Bundle_ID.
Here's my table structure:
The question is: how can I best insert each row of fields (bundle items) into their own row in the database (table: Bundle_Items), considering the number of rows will be different each time? I imagine a loop will be necessary when building the SQL query?
In other words, $_POST['item_name1'], $_POST['item_type1'], etc go into Bundle_Items as a single row.... and then $_POST['item_name2'], $_POST['item_type2'], etc go into Bundle_Items as another row.... until there are no more items to insert.
Here's how it works:
The user enters the bundle title and description, and can then add items below. For each item, there is a row of six fields. See screenshot. Using jQuery, I've made it so that the user can dynamically add additional rows of fields (limited to 50). Each field's name auto-increments according to its row (e.g. item_name1 for row 1, item_name2 for row 2).
When the form is submitted, PHP inserts the bundle (just the title and description, not the individual items) into the Bundles table and retrieves the newly created bundle's ID. The individual items will be stored in the Bundle_Items table, and will be associated with their parent bundle by Bundle_ID.
Here's my table structure:
"Bundles" Table
ID, Title, Description
"Bundle_Items" Table
Bundle_ID, ID, City, State, Type, Etc.
The question is: how can I best insert each row of fields (bundle items) into their own row in the database (table: Bundle_Items), considering the number of rows will be different each time? I imagine a loop will be necessary when building the SQL query?
In other words, $_POST['item_name1'], $_POST['item_type1'], etc go into Bundle_Items as a single row.... and then $_POST['item_name2'], $_POST['item_type2'], etc go into Bundle_Items as another row.... until there are no more items to insert.