I have a dynamic built with jQuery UI form where user can add new items in the form. I am trying to save them in my MySQL database as JSON. But with my current approach, only the last item of the form is being saved. How can I loop the array for each item from the POST values? My form is sending data as:
item_sl: 1
item_id: 14044
item_sl: 2
item_id: 14044
To prepare the data, I am using the following method. But as you can see, it doesn't loop for each item_sl
. So, it is saving only the last values.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$item_sl = trim($_POST["item_sl"]);
$item_id = trim($_POST["item_id"]);
foreach ($_POST["item_sl"] as $items) {
$rxData['items'][] = array(
'item_sl' => $items->item_sl,
'item_id' => $items->item_id,
);
}
$rxData = array(
'item_list' => array()
);
$rxJSON = json_encode($rxData, JSON_PRETTY_PRINT);
// MySQL insert
}
How can I prepare the array to loop for each item_sl
and prepare the JSON array for inserting?
The form has become complicated due to jQuery Sortable. But I'm attaching it below for clarification:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" action="" method="post">
<table id="sort" class="grid">
<thead>
<tr>
<th class="index">No.</th>
<th>Items</th>
<th>Serial</th>
<th>Item ID</th>
</tr>
</thead>
<tbody id="add">
</tbody>
</table>
<input type="submit" name="saveStay" value="Save" id="saveStay">
</form>
<script>
$(document).ready(function() {
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
},
updateIndex = function() {
$('td.index').each(function(i) {
$(this).html(i + 1);
});
$('input.indexInput').each(function(i) {
$(this).val(i + 1);
});
};
$("#sort tbody").sortable({
helper: fixHelperModified,
stop: updateIndex
}).disableSelection();
$("#addNew").click(function() {
var rx_text = $('#item_search').val();
var item_id = $('#item_id').val();
$('#add').append("<tr class='rem'><td class='index'>1</td><td>" +
rx_text +
"</td><td><input name='item_sl' class='indexInput' type='text' value='1'>" +
"</td><td><input name='item_id' type='text' value='" +
item_id +
"'></td></tr>");
updateIndex();
});
});
</script>