Reputation: 542
I created a table so user may add item dynamically. This is the table:
<table>
<tr class='master_added'>
<td>
<input type='text' class='id_act' name='arr_item[id_act]' value='1' />
<input type='text' class='val_status' name='arr_item[val_status]' value='SENT' />
</td>
<td>
<input type='text' name='arr_item[id_item]' class='id_item' value='ITEM_A' />
</td>
</tr>
<tr class='master_added'>
<td>
<input type='text' class='id_act' name='arr_item[id_act]' value='1' />
<input type='text' class='val_status' name='arr_item[val_status]' value='SENT' />
<input type='text' class='id_act' name='arr_item[id_act]' value='3' />
<input type='text' class='val_status' name='arr_item[val_status]' value='RECEIVED' />
</td>
<td>
<input type='text' name='arr_item[id_item]' class='id_item' value='ITEM_B' />
</td>
</tr>
<tr class='master_added'>
<td>
<input type='text' class='id_act' name='arr_item[id_act]' value='2' />
<input type='text' class='val_status' name='arr_item[val_status]' value='DELAYED' />
</td>
<td>
<input type='text' name='arr_item[id_item]' class='id_item' value='ITEM_B' />
</td>
</tr>
</table>
How to post this table value into database using a multidimensional array? Is the array I created even a correct one or easy to manipulate for loop?
This is the data after inserted to database:
t_item_master
ID_INSERT ID_ITEM
1 ITEM_A
2 ITEM_B
3 ITEM_B
t_item_detail
ID_INSERT ID_ACT ACT_VALUE
1 1 SENT
2 1 SENT
2 3 RECEIVED
3 2 DELAYED
Note: I'd like to use last insert id on t_item_master
for the ID_INSERT
on t_item_detail
Upvotes: 1
Views: 329
Reputation: 1423
You are almost there but. You input fields needs to specify they are arrays. You can do it by simply adding [] at the end of names, so for example:
<input type='text' class='id_act' name='arr_item[id_act][]' value='2' />
Notice []
in arr_item[id_act][]
which will allow you to loop in php. For this variable you can do loop in php like this:
<?php
foreach($_POST['arr_item']['id_act'] as $id_act) {
echo $id_act;
}
?>
To use last INSERT ID in MySQL, you can use MySQL function LAST_INSERT_ID(). From example give here https://dev.mysql.com/doc/refman/5.7/en/getting-unique-id.html you can do your queries:
INSERT INTO t_item_detail (ID_INSERT, ID_ACT, ACT_VALUE)
VALUES(null, value,'value');
INSERT INTO t_item_master (ID_INSERT, ID_ITEM)
VALUES(LAST_INSERT_ID(),'value');
Upvotes: 1