简体   繁体   中英

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/

   <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

<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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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