1

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>
Hijibiji
  • 428
  • 4
  • 20
  • Why don't you send an array since you have multiple values for the same key? – pr1nc3 Aug 17 '21 at 13:44
  • @pr1nc3, I have updated the question with the form I'm working with. Can you please have a look? – Hijibiji Aug 17 '21 at 14:15
  • Since you are working with array, you have to submit input as array – vaske Aug 17 '21 at 14:18
  • check this out https://stackoverflow.com/a/3314581/16039 – vaske Aug 17 '21 at 14:19
  • @vaske, Thanks, I have tried to submit using an array following your suggestion. But it is not returning any value. I have updated the question with the updated `POST` method. Can you please have a look if I am doing it in right way? – Hijibiji Aug 17 '21 at 14:59

1 Answers1

1

First, update the two input names as name='item_sl[]' and name='item_id[]'. These will post your values as array. Then loop the values and format them as JSON as required. For example, with the following loop,

$rxData = array(
    'items' => array()
);
foreach(item_sl as $key => $n) {
    $rxData['items'][] = array(
        'item_sl' => $n,
        'item_id' => item_id[$key]
    );
}

You will get a JSON structured as below.

{
   "items":[
      {
         "item_sl":"1",
         "item_id":"1234"
      },
      {
         "item_sl":"2",
         "item_id":"2345"
      }
   ]
}
Ashonko
  • 533
  • 8
  • 34