Ashonko
Ashonko

Reputation: 613

How to loop through multiple dynamic input fields in php to insert them in mysql table?

I have a table named item in my mySql database with the columns named item and price. With jquery, I used a button that generates fields for the input of multiple items and their price. But what should be the php codes for looping through the inputs for inserting them respectively? (Like item 1 with price 1) Some thing like this that I'm trying to achieve

<script>
$(document).ready(function() {
    var count = 0;

    $('p#add_field').click(function(e) {
        e.preventDefault();
        count += 1;
        $('#container').append(
            'Item: <input type="text" id="item_' + count + '" name="item[]' + '"/>\n\
             Unit price: <input type="text" id="price_' + count + '" name="price[]' + '"/><br>'
        );
    });

});
</script>

<?php
if (isset($_POST['btnSubmit'])) {
    if ($_POST['item']) {

        foreach ($_POST['item'] as $key => $value) {
            $sql_item    = sprintf("INSERT INTO item (item) VALUES ('%s')", mysql_real_escape_string($value));
            $result_item = $db->query($sql_item);
        }        
    }
    echo "<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> item(s) added for this user!</h1>";
    $db->kill();
}
?>
<?php if (!isset($_POST['btnSubmit'])) { ?>
    <form action="" method="POST">
        <div id="container">
            <label>Available items</label>
            <p id="add_field"><button type="button" href="#">Add new item</button></p>
        </div>
        <button type="submit" name="btnSubmit">Save items</button>
    </form>
<?php } ?>

Upvotes: 0

Views: 1098

Answers (1)

MinistryOfChaps
MinistryOfChaps

Reputation: 1484

Your storage of data is abnormal, change the item table so it has an auto increment ID column and an item name and item price column.

Change your code in the foreach loop to reflect the table change.

Your approach to sanitizing your SQL query is not the best way, you are using mySQLi to connect to the database so use the class' built in function to prepare and execute queries.

Upvotes: 1

Related Questions