如何在mysql表中使用foreach循环插入一个静态和多个动态值?

时间:2017-10-05 07:59:12

标签: javascript php jquery mysql

在我的表单中,我有一个名为Product的字段和一个名为Add new的按钮,用于在名为WeightUnit price的每次点击中添加2个字段。现在,我如何INSERT使用php在我的mysql表格中product这个表单的值?如何为WeightUnit price值的每个输入循环Rice值?

这是我想要实现的一个示例:产品有一个值Weight和两组Unit price10, 50值,20, 45和{分别为{1}}。由于phpRiceAvailable options的值为2组,因此sql部分循环INSERT 2次会是什么mysql表(下面描述的结构)?

Sample

MySQL表结构是:

CREATE TABLE IF NOT EXISTS `product_table` (
  `ID` int(11) NOT NULL,
  `product_name` varchar(30) NOT NULL,
  `weight` int(10) NOT NULL,
  `price` int(10) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

此处,ID为PRIMARY KEY并设为AUTO_INCREMENT

这是表单的jqueryhtml部分:

$(document).ready(function() {
        var wrapper = $(".input_fields_wrap");
        var count = 0;

        $('p#add_field').click(function(e) {
            e.preventDefault();
            count += 1;
            $('#container').append(
                '<div>\n\
                   <label>Weight</label><input type="text" id="weight_' + count + '" name="weight[]' + '"/>\n\
                  <label>Unit price</label><input type="text" id="price_' + count + '" name="price[]' + '"/>\n\
                <a href="#" class="remove_field">Remove</a><br>'
            );
        });

        $(wrapper).on("click", ".remove_field", function(e) { 
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        })
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST">
   <label>Product</label><input type="text" id="product" name="product"><br>
   <div id="container" class="input_fields_wrap">
      <label>Available options:</label>
      <div>
         <p id="add_field"><button type="button" href="#"><span>Add new</span></button></p>
      </div>
   </div>
   <button type="submit" name="btnSubmit">Save to database</button>
</form>

这是样本fiddle。该表单的php动作代码应该起什么作用?

2 个答案:

答案 0 :(得分:1)

您好您可以在PHP中使用以下代码

<?php
for($ri=0; $ri<count($_POST["weight"]); $ri++){
   $sql = "INSERT INTO product_table (product_name, weight, price) VALUES ('".$_POST["product"]."', '".$_POST["weight"][$ri]."', '".$_POST["price"][$ri]."')";

   //Execute $sql in here with your connection 
}

修改

<?php
for($ri=0; $ri<count($_POST["weight"]); $ri++){
   $sql = "INSERT INTO product_table (product_name, weight, price) VALUES ('".$_POST["product"]."', '".$_POST["weight"][$ri]."', '".$_POST["price"][$ri]."')";

   if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
   } else {
    echo "Error: " . $sql . "<br>" . $conn->error;
   }
}

答案 1 :(得分:1)

您可以使用我一直用于解决这些问题的内容。

将您的表单更新为: -

<form action="" method="POST">
   <input type="hidden" name="count" id="count" value="0">
   <label>Product</label><input type="text" id="product" name="product"><br>
   <div id="container" class="input_fields_wrap">
      <label>Available options:</label>
      <div>
         <p id="add_field"><button type="button" href="#"><span>Add new</span></button></p>
      </div>
   </div>
   <button type="submit" name="btnSubmit">Save to database</button>
</form>

您注意到我添加了一个名为count的隐藏字段。 count变量将检查将添加多少行和列。

您的JS将成为: -

<script>
    $(document).ready(function() {
        var wrapper = $(".input_fields_wrap");

        $('p#add_field').click(function(e) {
            var count = $("#count").val();//get the current value of count variable
            e.preventDefault();
            count += 1;
            $('#container').append(
                '<div>\n\
                   <label>Weight</label><input type="text" id="weight_' + count + '" name="weight_' + count + '"/>\n\
                  <label>Unit price</label><input type="text" id="price_' + count + '" id="price_' + count + '"/>\n\
                <a href="#" class="remove_field">Remove</a><br>'
            );
            //now update back the count variable value
            $("#count").val(count);
        });

        $(wrapper).on("click", ".remove_field", function(e) { 
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        })
    });
</script>

现在,每次添加字段时,其名称都会变为weight_countValprice_countVal,可以通过后端轻松访问。

你的后端php看起来像: -

$totalRows = $_POST['count']; //the hidden variable keeping count of total rows

for($i=1;$i<=$totalRows;$i++)
{
  $weight = $_POST['weight_'.$i];
  $price = $_POST['price_'.$i];
  //run your insert commands here 
}