简体   繁体   English

从动态表单向数据库插入数据数组

[英]insert data array from dynamic form to database

i have a dynamic form. 我有一个动态的形式。 in form i can add multiple field as much as I want. 在表格中,我可以根据需要添加多个字段。 but I am confused how to save it into the database. 但是我很困惑如何将其保存到数据库中。

this my form code, just like this but little diferent https://jsfiddle.net/Twisty/q8zj00s0/1/ 这是我的表单代码,就像这样,但有点不同https://jsfiddle.net/Twisty/q8zj00s0/1/

   <form id="tambahepisode" method="post" style="margin-bottom: 20px;"></form>
<form>
  <ul id="fieldList">
    <li>
      <input name="name[]" type="text" placeholder="Name" form="tambahepisode"/>
    </li>
    <li>
      <input name="phone[]" type="text" placeholder="Phone" form="tambahepisode"/>
    </li>
    <li>
      <input name="email[]" type="text" placeholder="E-Mail" form="tambahepisode"/>
    </li>
  </ul>
  <button id="addMore">Add more fields</button>
  <br>
  <br>
  <input type="submit" name="submit" class="btn btn-default" value="Publikasi" form="tambahepisode" style="width: 100%;" />
</form>

and here my jquery to create dynamic form 这是我的jQuery创建动态表格

<script type="text/javascript">
    $(function() {
  $("#addMore").click(function(e) {
    e.preventDefault();
    $("#fieldList").append("<li>&nbsp;</li>");
    $("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
    $("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
    $("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
  });
});

</script>

my basic insert to database 我基本插入数据库

if(isset($_POST['submit'])){
        $name= htmlentities($_POST['name']);
        $phone= htmlentities($_POST['phone']);
        $email= htmlentities($_POST['email']);
        $query = $db->prepare("INSERT INTO `data`(`name`,`phone`,`email`)
        VALUES (:name,:phone,:email)");
        $query->bindParam(":name", $name);
        $query->bindParam(":phone", $phone);
        $query->bindParam(":email", $email);
        $query->execute();
        header("location: index.php");
    }

At first you have to count how much no of record you want to save, as you want save array by add more button. 首先,您必须计算要保存的记录数,因为要通过添加更多按钮保存数组。

For example count name or any other field. 例如,计数名称或任何其他字段。

$count = count($_POST['name']);

Then use foreach or for loop. 然后使用foreach或for循环。

for($i=0;$i<$count;$i++){
    $name= htmlentities($_POST['name'][$i]);
    $phone= htmlentities($_POST['phone'][$i]);
    $email= htmlentities($_POST['email'][$i]);
    $query = $db->prepare("INSERT INTO `data`(`name`,`phone`,`email`)
        VALUES (:name,:phone,:email)");
    $query->execute();        
}
header("location: index.php");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM