如何循环每行中的每个输入并将其插入数据库?

时间:2016-04-24 10:17:36

标签: php jquery

我有一个未定义输入数量的表单。

Here is the image of the sample form

单击“提交”时,应将每行插入具有不同ID的数据库中。 (例如,第1行应该有id#100,第2行-id#101)我的问题是我不知道如何循环每行中的每个输入。

HTML代码

<form action="addnewhousehold.php" method="POST">       
     <table class="table table-striped" id="table-form">
         <thead>
             <tr>
                 <th>Firstname</th>
                 <th>Middlename</th>
                 <th>Lastname</th>
                 <th>Extension name</th>
             </tr>
         </thead>
         <tbody>
             <tr>
                <td><input type="text" name="firstname[]" id="firstname"></td>
                <td><input type="text" name="middlename[]" id="middlename"></td>
                <td><input type="text" name="lastname[]" id="lastname"></td>
                <td><input type="text" name="extension_name[]" id="extension_name"></td>
             </tr>
         </tbody>
     </table>
     <a id="moreinput"><span class="fa fa-plus fa-fw"></span> Add more input</a>
</form>

JS代码(来源:http://jsfiddle.net/2HGdv/13/

  $(document).ready(function(){


       $("#moreinput").on('click', function(e){
            e.preventDefault();

            $("#table-form").each(function(){
                 var td = '<tr>';
                 $.each($('tr:last td', this), function(){
                     td += '<td>' + $(this).html() + '</td>';
                 });
                 td += '</tr>';

                  $(this).append(td);
             });
        });
   }); 

PHP代码

   <?php
         require 'connectdb.php';

            foreach ($_POST['firstname'] as $fname) {
                // I DON'T KNOW haha
           }
   ?>

2 个答案:

答案 0 :(得分:1)

<?php
//// set conecction DB
//$servername = "localhost";
//$username = "username";
//$password = "password";
//$dbname = "myDB";

//// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
//// Check connection
//if ($conn->connect_error) {
//    die("Connection failed: " . $conn->connect_error);
//}

require 'connectdb.php';

$sql = "INSERT INTO Table_Name (`firstname`, `middlename`, `lastname`, `extension_name`) VALUES ";
foreach ($_POST['firstname'] as $kay=>$value) {
// $sql .= '' | $sql = $sql . '';
$sql .= "('{$value}','{$_POST['middlename'][$kay]}','{$_POST['lastname'][$kay]}','{$_POST['extension_name'][$kay]}',),";
}
// remove last `,` into query;
$sql = rtrim($sql,',');

$countRow = count($_POST['firstname']);

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

// close DB conection
$conn->close();
?>

答案 1 :(得分:0)

如果您只发布表单字段,则可以执行以下操作:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

这将遍历POST请求中的任何参数。