tmrhmdv
tmrhmdv

Reputation: 172

Adding multiple records to a database from a single form?

I have a form where I can add items to the inventory. Currently, I can add only one item at a time. Here's the form screenshot: https://i.sstatic.net/1vHYr.png. But I want to accomplish this: https://i.sstatic.net/yGy8S.png (< just a sketch), which is adding multiple records to the database using one form. These are my current forms:

add.html:

<form action="add.php" method="POST">
    <select name="category" id="category">
      <option value="1">Caviar In Canned Jars</option>
    </select>
    <input id="name" name="name" type="text">
    <input id="size" name="size" type="text">
    <input id="sku" name="sku" type="text">
    <input id="price" name="price" type="text">
    <input value="Add" type="submit">
</form>

add.php:

$result = mysql_query("
    INSERT INTO `items` (name, size, sku, price, category_id)
    VALUES ('$_POST[name]', '$_POST[size]', '$_POST[sku]', '$_POST[price]', '$_POST[category]');");
    if (!$result) {
        echo "Something went wrong!";
    } else {
    echo '<script type="text/javascript">
                <!--
                    window.location = "add.html"
                //-->
          </script>';
}

How can I achieve the functionality in the second screenshot with PHP and SQL (https://i.sstatic.net/yGy8S.png)?

P.S.: I'm aware that it's prone to SQL injection, but it's only running on local web server

Upvotes: 2

Views: 6380

Answers (1)

evan
evan

Reputation: 12535

Step 1. Change the html bits to be arrays of data by adding brackets after the input names.

<form action="add.php" method="POST">
    <!-- row 1 -->
    <select name="category[]" id="category">
      <option value="1">Caviar In Canned Jars</option>
    </select>
    <input id="name" name="name[]" type="text">
    <input id="size" name="size[]" type="text">
    <input id="sku" name="sku[]" type="text">
    <input id="price" name="price[]" type="text">
    <!-- row 2 -->
    <select name="category[]" id="category">
      <option value="1">Caviar In Canned Jars</option>
    </select>
    <input id="name" name="name[]" type="text">
    <input id="size" name="size[]" type="text">
    <input id="sku" name="sku[]" type="text">
    <input id="price" name="price[]" type="text">
    <!-- submit at bottom -->
    <input value="Add" type="submit">
</form>

There will be only one submit. And the post will hold all the data in arrays.

Step 2. Loop through the data either doing individual inserts or constructing a large query.

In this example there are 5 rows of data.

for($i = 0; $i < 5; $i++)
{
    $name = $_POST['name'][$i];
    $size = $_POST['size'][$i];
    ...

    /* verify data, do sql escaping */

    $result = mysql_query("
        INSERT INTO `items` (name, size, sku, price, category_id)
        VALUES ('$name', '$size', '$sku', '$price', '$category');
    ");

   /* do result handling */
}

Upvotes: 3

Related Questions