如何遍历动态生成的表行并获取php

时间:2017-02-13 12:34:33

标签: php jquery html

我将非常感谢您对此的指导。 我有一个包含大约4个字段的HTML表单,其值被发布到tr行 在表中,使用jquery动态生成行。点击 在输入字段中的值后提交按钮,值被发送到我的数据库表。这里的问题是在我的PHP代码中,我似乎无法 能够循环遍历表以获取这些值。我的代码是 如下所示:

HTML

<form action="" method="post" role="form"  class="form-horizontal">
  <div class="form-group">
     <input type="text" class="form-control" name="name[]" id="name">
  </div>
  <div>
     <input type="text" class="form-control" name="age[]" id="age"  />
  </div>
  <div>
      <input type="text" class="form-control" name="sex[]" id="sex"  />
  </div>
   <div>
      <input type="text" class="form-control" name="scores[]" id="scores" />
   </div>
   <div>
        <button type="button" class="btn btn-success" name="add_records[]"
id="add_records">ADD ROW</button>
   </div>
   </div>
    <div class="form-group">
        <button type="submit" class="btn btn-success name="submit_rec">Submit</button>
    </div>
</form>

PHP PART

<?php
      if (isset($_POST['submit_rec'])){
        $conn = mysqli_connect('localhost', 'root', '', 'proj');

//processing the fied for name for instance
         if ($_POST['name']){
                $name = mysqli_real_escape_string($conn, $_POST['name]);
                foreach ($name as $value) {
                echo $value; // does not echo any value, same with other fields!
        }
      }
    }
?>

和JQUERY PART

<script language='JavaScript'>
        //script to add new table row
    $(document).ready(function(){
       var i=1;
    $("#add_records").click(function(){
        var name = $("#name").val();
        var age = $("#age").val();
        var sex = $("#sex").val();
        var scores= $("#scores").val();
        var delRow ='<button type="button" class="btn btn-danger my_butn"
id="del_btn"> - </button>';

        $("table tbody").append("<tr><td>"+i+"</td><td>"+name+"</td><td>"+age+"</td><td>"+sex+"</td><td>"+scores+"</td><td>"+delRow+"</td></tr>");
       $("tr>td:last").addClass('delete').addClass('del');
        i++;
</script>

1 个答案:

答案 0 :(得分:0)

用,

替换你的php部分
  <?php
if (isset($_POST['submit_rec'])) {
    $conn = mysqli_connect('localhost', 'root', '', 'proj');

    //processing the fied for name for instance
    if ($_POST['name']) {
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        foreach ($name as $value) {
            echo $value; // does not echo any value, same with other fields!
        }
    }
}
?>

尝试一下,它会起作用。