PHP Dynamic row insert and update values in to database

Hello friend I am developing a web application and I have created a dynamic in which when I click add more button it adds more rows into the form and then click submit it passes all values to the database through a for loop iteration

But currently, I have been struck at one point where when a user wants to make some changes in the form I have no idea how to do the update and insert the query into DB

for example, if the user already submitted the dynamic form to db and later the user wants to make some changes in the already inserted dynamic form and add a few new rows to the same form I don’t have any idea how to do that I need some help from my fellow stack overflow community

so below is the full code which is quite long, feel free to check and help me to go through this

Material_request.php page

                        <?php
                                    if ($requestNo) {

                                        $query = "SELECT * FROM material_requests WHERE request_no = '$requestNo'";
                                        $result = mysqli_query($con, $query);


                                        if (mysqli_num_rows($result) > 0) {
                                            while ($row = mysqli_fetch_assoc($result)) {

                                                $select_item = "SELECT * FROM itemregistration WHERE id = ?";
                                                $stmt = mysqli_prepare($con, $select_item);
                                                mysqli_stmt_bind_param($stmt, "s", $row['item_name']);
                                                mysqli_stmt_execute($stmt);
                                                $result_itemName = mysqli_stmt_get_result($stmt);

                                                $row_itemName = mysqli_fetch_assoc($result_itemName);

                                                if ($row_itemName) {
                                                    // Sanitize data before displaying
                                                    $name = htmlspecialchars($row_itemName['name']);
                                                    // Similarly, sanitize other fields if needed

                                                    ?>
                                                    <div class="form-group addmoreFormGroup" style="margin-top: 30px;">
                                                        <div class="col-lg-1" style="text-align: center;"
                                                             hidden="hidden">
                                                            <div class="col-lg-12">
                                                                <p class="para" style="margin-top: 30px" id="number">
                                                                    1. </p>
                                                            </div>
                                                        </div>
                                                        <div class="col-lg-3">
                                                            <label style="margin-left: 16px" class="control-label">Item
                                                                Name: </label>
                                                            <div class="col-lg-12">
                                                                <input type="text" id="itemName" name="itemName"
                                                                       class="form-control"
                                                                       onkeyup="autocompleteName();"
                                                                       value="<?php echo $name ?> ">
                                                                <input name="id1" id="id1" type="hidden">
                                                            </div>
                                                        </div>
                                                        <!--                                        <div class="col-lg-4">-->
                                                        <!--                                            <label style="margin-left: 16px" class="control-label">Item Code:</label>-->
                                                        <!--                                            <div class="col-lg-12">-->
                                                        <!--                                                <input name="itemCode[]" style="width: 100%; height: 40%"-->
                                                        <!--                                                       class="form-control" readonly/>-->
                                                        <!--                                            </div>-->
                                                        <!--                                        </div>-->
                                                        <div class="col-lg-2" style="margin-bottom: 30px">
                                                            <label style="margin-left: 16px" class="control-label">Requested
                                                                Qty:
                                                                <span style="color: #CA0609;">*</span>
                                                            </label>
                                                            <div class="col-lg-12">
                                                                <input name="reqQty[]" style="width: 100%; height: 40%"
                                                                       class="form-control"
                                                                       value="<?php echo $row['request_qty'] ?>"
                                                                       required>
                                                            </div>
                                                        </div>
                                                        <div class="col-lg-2" style="margin-bottom: 30px">
                                                            <label style="margin-left: 16px" class="control-label">Unit
                                                                of
                                                                Measure:
                                                                <span style="color: #CA0609;">*</span>
                                                            </label>
                                                            <div class="col-lg-12">
                                                                <input name="Uom[]" style="width: 100%; height: 40%"
                                                                       class="form-control"
                                                                       value="<?php echo $row['unit_of_measure'] ?>"
                                                                       required>
                                                            </div>
                                                        </div>
                                                        <div class="col-lg-4">
                                                            <label for="Sremark" class="control-label col-lg-12">Special
                                                                Remark
                                                                <span style="color: #CA0609;">*</span>
                                                            </label>
                                                            <div class="col-lg-12">
                                                                <textarea class="form-control" name="Sremark[]"
                                                                          id="Sremark"
                                                                          required><?php echo htmlspecialchars($row['special_remark']); ?></textarea>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php
                                                }
                                            }

                                            ?>

                                            <div class="form-group col-lg-12">
                                                <div class="col-lg-3">
                                                    <button type="button" class="btn btn-success add-more-insert"
                                                            style="font-weight: bold; margin-bottom: 20px;">Add
                                                        More
                                                    </button>
                                                </div>
                                            </div>

                                            <?php
                                        } else {
                                            ?>

                                            <div class="form-group addmoreFormGroup" style="margin-top: 30px;">
                                                <div class="col-lg-1" style="text-align: center;" hidden="hidden">
                                                    <div class="col-lg-12">
                                                        <p class="para" style="margin-top: 30px" id="number">1. </p>
                                                    </div>
                                                </div>
                                                <div class="col-lg-3">
                                                    <label style="margin-left: 16px" class="control-label">Item
                                                        Name:
                                                        <span style="color: #CA0609;">*</span>
                                                    </label>
                                                    <div class="col-lg-3">
                                                        <label style="margin-left: 16px" class="control-label">Item
                                                            Name: </label>
                                                        <div class="col-lg-12">
                                                            <input type="text" id="itemName" name="itemName"
                                                                   class="form-control" onkeyup="autocompleteName();">
                                                            <input name="id1" id="id1" type="hidden">
                                                        </div>
                                                    </div>
                                                </div>
                                                <!--                                        <div class="col-lg-4">-->
                                                <!--                                            <label style="margin-left: 16px" class="control-label">Item Code:</label>-->
                                                <!--                                            <div class="col-lg-12">-->
                                                <!--                                                <input name="itemCode[]" style="width: 100%; height: 40%"-->
                                                <!--                                                       class="form-control" readonly/>-->
                                                <!--                                            </div>-->
                                                <!--                                        </div>-->
                                                <div class="col-lg-2" style="margin-bottom: 30px">
                                                    <label style="margin-left: 16px" class="control-label">Requested
                                                        Qty:
                                                        <span style="color: #CA0609;">*</span>
                                                    </label>
                                                    <div class="col-lg-12">
                                                        <input name="reqQty[]" style="width: 100%; height: 40%"
                                                               class="form-control" required/>
                                                    </div>
                                                </div>
                                                <div class="col-lg-2" style="margin-bottom: 30px">
                                                    <label style="margin-left: 16px" class="control-label">Unit of
                                                        Measure:
                                                        <span style="color: #CA0609;">*</span>
                                                    </label>
                                                    <div class="col-lg-12">
                                                        <input name="Uom[]" style="width: 100%; height: 40%"
                                                               class="form-control" required/>
                                                    </div>
                                                </div>
                                                <div class="col-lg-4">
                                                    <label for="Sremark" class="control-label col-lg-12">Special
                                                        Remark
                                                        <span style="color: #CA0609;">*</span>
                                                    </label>
                                                    <div class="col-lg-12">
                                                    <textarea class="form-control" name="Sremark[]"
                                                              id="Sremark[]" required></textarea>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="form-group col-lg-12">
                                                <div class="col-lg-3">
                                                    <button type="button" class="btn btn-success add-more-insert"
                                                            style="font-weight: bold; margin-bottom: 20px;">Add
                                                        More
                                                    </button>
                                                </div>
                                            </div>

                                            <?php
                                        }
                                    } else {
                                        ?>

                                        <div class="form-group addmoreFormGroup" style="margin-top: 30px;">
                                            <div class="col-lg-1" style="text-align: center;" hidden="hidden">
                                                <div class="col-lg-12">
                                                    <p class="para" style="margin-top: 30px" id="number">1. </p>
                                                </div>
                                            </div>
                                            <div class="col-lg-3">
                                                <label style="margin-left: 16px" class="control-label">Item
                                                    Name: </label>
                                                <div class="col-lg-12">
                                                    <input type="text" id="itemName" name="itemName"
                                                           class="form-control" onkeyup="autocompleteName();">
                                                    <input  name="id1" id="id1" type="text" hidden="hidden">
                                                </div>
                                            </div>
                                            <!--                                        <div class="col-lg-4">-->
                                            <!--                                            <label style="margin-left: 16px" class="control-label">Item Code:</label>-->
                                            <!--                                            <div class="col-lg-12">-->
                                            <!--                                                <input name="itemCode[]" style="width: 100%; height: 40%"-->
                                            <!--                                                       class="form-control" readonly/>-->
                                            <!--                                            </div>-->
                                            <!--                                        </div>-->
                                            <div class="col-lg-2" style="margin-bottom: 30px">
                                                <label style="margin-left: 16px" class="control-label">Requested
                                                    Qty:
                                                    <span style="color: #CA0609;">*</span>
                                                </label>
                                                <div class="col-lg-12">
                                                    <input name="reqQty[]" style="width: 100%; height: 40%"
                                                           class="form-control" required/>
                                                </div>
                                            </div>
                                            <div class="col-lg-2" style="margin-bottom: 30px">
                                                <label style="margin-left: 16px" class="control-label">Unit of
                                                    Measure:
                                                    <span style="color: #CA0609;">*</span>
                                                </label>
                                                <div class="col-lg-12">
                                                    <input name="Uom[]" style="width: 100%; height: 40%"
                                                           class="form-control" required/>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <label for="Sremark" class="control-label col-lg-12">Special
                                                    Remark
                                                    <span style="color: #CA0609;">*</span>
                                                </label>
                                                <div class="col-lg-12">
                                                    <textarea class="form-control" name="Sremark[]"
                                                              id="Sremark[]" required></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="form-group col-lg-12">
                                            <div class="col-lg-3">
                                                <button type="button" class="btn btn-success add-more-insert" value="1" onclick="addMore"
                                                        style="font-weight: bold; margin-bottom: 20px;">Add
                                                    More
                                                </button>
                                            </div>
                                        </div>

                                        <?php
                                    }
                                    ?>

Javascript part of the dynamic form

  function autocompleteName() {
        $("#itemName").autocomplete({
            source: "fetch_items.php",
            minLength: 1,
            select: function (event, ui) {
                $('#id1').val(ui.item.id);
                return false;
            }
        });
    }

    $(document).ready(function () {
        $('.tempSave').click(function () {
            // Create a FormData object to send files
            var formData = new FormData($('#purchaseorderForm')[0]);
            formData.append('tempSave', 1); // Add a flag to indicate temporary save

            // Send AJAX request
            $.ajax({
                type: 'POST',
                url: 'submit_materialRequestTemp.php',
                data: formData,
                processData: false, // Prevent jQuery from automatically processing data
                contentType: false, // Prevent jQuery from setting contentType
                success: function (response) {
                    // Handle success response
                    alert('Data temporarily saved successfully!');
                    console.log(response); // Log the response for debugging
                },
                error: function (xhr, status, error) {
                    // Handle error
                    alert('Error occurred while saving data.');
                    console.error(xhr.responseText); // Log the error response for debugging
                }
            });
        });
    });


    function selectCode(selectElement) {
        var selectedItemId = $(selectElement).val();
        var itemCodeInput = $(selectElement).closest('.addmoreFormGroup').find('input[name="itemCode[]"]');

        // Make an AJAX call to fetch the item code based on the selected item ID
        $.ajax({
            url: 'get_item_code.php',
            type: 'POST',
            data: {item_id: selectedItemId},
            success: function (response) {
                // Log the response to the console for debugging
                console.log(response);
                // Set the item code input value within the same row
                itemCodeInput.val(response);
            },
            error: function (xhr, status, error) {
                // Log any errors to the console
                console.error(xhr.responseText);
                // Optionally, display an error message to the user
                alert('Error fetching item code');
            }
        });
    }

    var count = 2; // Initial row count

    // Add more when only inserting
    $('.add-more-insert').click(function () {
        // Check if the static row and all existing dynamic rows are filled
        if (isStaticRowFilled() && areDynamicRowsFilled()) {
            var newFormGroup = createFormGroup(count);
            $('.addmoreFormGroup:last').after(newFormGroup);
            count++;
        } else {
            alert('Fill the static row and existing dynamic rows before adding a new row.');
        }
    });

    function isStaticRowFilled() {
        // Check if the static row is filled
        var itemName = $('#itemName').val();
        var reqQty = $('input[name="reqQty[]"]').val();
        var Uom = $('input[name="Uom[]"]').val();
        var Sremark = $('textarea[name="Sremark[]"]').val();

        return itemName !== '' && reqQty !== '' && Uom !== '' && Sremark !== '';
    }

    function areDynamicRowsFilled() {
        var areFilled = true;

        // Check each existing dynamic row
        $('.addmoreFormGroup').each(function () {
            var itemName = $(this).find('#itemName').val();
            var reqQty = $(this).find('input[name="reqQty[]"]').val();
            var Uom = $(this).find('input[name="Uom[]"]').val();
            var Sremark = $(this).find('textarea[name="Sremark[]"]').val();

            // If any dynamic row is not filled, set areFilled to false
            if (itemName === '' || reqQty === '' || Uom === '' || Sremark === '') {
                areFilled = false;
                return false; // exit the loop
            }
        });

        return areFilled;
    }

    $('form').submit(function () {
        // Check if the static row and all existing dynamic rows are filled
        if (isStaticRowFilled() && areDynamicRowsFilled()) {
            // The form is filled, proceed with submission
            return true;
        } else {
            alert('Fill all rows before submitting the form.');
            return false; // Prevent form submission
        }
    });

    // Remove form group
    $(document).on('click', '.remove-form-group', function () {
        var formGroup = $(this).closest('.addmoreFormGroup');
        formGroup.remove();
        count--;

        // Update the remaining row numbers
        updateRowNumbers();
    });

    function createFormGroup(number) {
        var formGroup = `
        <div class="form-group col-lg-12 addmoreFormGroup">
            <div class="col-lg-1" style="text-align: center;" hidden = "hidden">
                <div class="col-lg-12">
                    <p class="para" style="margin-top: 30px" id="number">${number}. </p>
                </div>
            </div>
           <div class="col-lg-3">

                                            <div class="col-lg-12">
                                                <input type="text" id="itemName" name="itemName"
                                                       class="form-control" onkeyup="autocompleteName();">
                                                <input  name="id1" id="id1" type="text" hidden="hidden">
                                            </div>
                                        </div>

            <div class="col-lg-2" style="margin-bottom: 30px">

                <div class="col-lg-12">
                    <input name="reqQty[]" style="width: 100%; height: 40%" class="form-control"/>
                </div>
            </div>

            <div class="col-lg-2" style="margin-bottom: 30px">

                <div class="col-lg-12">
                    <input name="Uom[]" style="width: 100%; height: 40%" class="form-control"/>
                </div>
            </div>

            <div class="col-lg-3">

                <div class="col-lg-12">
                    <textarea class="form-control" name="Sremark[]" id="Sremark[]"></textarea>
                </div>
            </div>

            <div class="col-lg-2">
                <button style="margin-top: 35px; margin-left: 18px" class="remove-form-group btn btn-danger">Remove</button>
            </div>
        </div>
    </div>`;

        return formGroup;
    }

    function updateRowNumbers() {
        $('.addmoreFormGroup').each(function (index) {
            $(this).find('#number').text(index + 1 + '.');
        });
    }

    // Update button click event
    $('#tUpdate').click(function (e) {
        e.preventDefault(); // Prevent default form submission

        // Serialize form data
        var formData = $('#purchaseorderForm').serialize();

        // Append the count of added rows to the form data
        formData += '&addedRows=' + (count - 2); // Subtract 2 to exclude the initial row and the first dynamic row

        // Send form data asynchronously
        $.post('updateMaterialRequest.php', formData)
            .done(function (response) {
                // Handle success
                console.log(response); // Log the response
                // You can handle success message or redirect here if needed
            })
            .fail(function (xhr, status, error) {
                // Handle failure
                console.error(xhr.responseText); // Log error response
                // You can handle failure message here
            });
    });
</script>


please help me to find a way to update the values

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật