2017-04-24 83 views
-1

我有一个允许用户添加和删除行的表单。我使用POST将值发送到PHP页面以将值插入到MySQL数据库中。我可以提交静态行,但无法弄清楚如何循环并在表单上插入所有行,因为它是可变的(用户可以添加或删除行)。有人可以请告诉我如何完成通过PHP插入所有行。 我知道如何建立连接,这不是问题。提供的任何帮助将不胜感激。通过PHP插入带有变量行的HTML表格

我的HTML表单:

<!DOCTYPE html> 
 

 
<html> 
 

 
<head> 
 
    <title> 
 
    </title> 
 
</head> 
 

 
<body> 
 
    <form action="/SubmitTest.php" method="post"> 
 
    <table class="table table-striped table-bordered" id="mytable"> 
 
     <tbody> 
 
     <tr> 
 
      <td>{{$index+1}}</td> 
 

 
      <td><input id="{{'CustomerName-'+$index}}" name="CustomerName[]"></td> 
 

 
      <td><input id="{{'Employee-'+$index}}" name="Employee[]"></td> 
 

 
      <td><input id="{{'Cash-'+$index}}" name="CashAmt[]"></td> 
 

 
      <td><input id="{{'Check-'+$index}}" name="CheckAmt[]"></td> 
 

 
      <td><input id="{{'Total-'+$index}}" name="Total[]"></td> 
 

 
      <td><input id="{{'Invoice-'+$index}}" name="Invoice[]"></td> 
 

 
      <td><button class="btn btn-danger">Delete</button></td> 
 
     </tr> 
 
     </tbody> 
 
    </table> 
 

 
    <div class="new row"><button class="btn btn-success" type="button">Add Row</button></div> 
 
    </form> 
 
</body> 
 

 
</html>

+3

这里没有PHP代码,所以这不是堆栈溢出问题,而是某种工作顺序。如果你还没有做过很多PHP并想为此构建一个后端,请评估各种[开发框架](http://codegeekz.com/best-php-frameworks-for-developers/)并选择一款适合您的风格和需求的产品。 [Laravel](http://laravel.com/)在这里得到很好的支持并且非常容易。 – tadman

回答

0

遍历所有的输入参数。

$stmt = mysqli_prepare($conn, "INSERT INTO yourTable (customerName, employee, cashAmt, checkAmt, total, invoice) 
    VALUES (?, ?, ?, ?, ?, ?)"); 
mysqli_stmt_bind_param($stmt, "ssiiis", $customerName, $employee, $cashAmt, $checkAmt, $total, $invoice) 
foreach ($_POST['CustomerName'] as $i => $customerName) { 
    $employee = $_POST['Employee'][$i]; 
    $cashAmt = $_POST['CashAmt'][$i]; 
    $checkAmt = $_POST['CheckAmt'][$i]; 
    $totel = $_POST['Totel'][$i]; 
    $invoice = $_POST['Invoice'][$i]; 
    mysqli_stmt_execute($stmt); 
} 
+0

如果其中一个不是必需的,并且他们跳过例如员工,会发生什么情况?绑定/准备将失败。 – clearshot66

+0

您可以在调用execute之前添加验证检查。 – Barmar

+0

或者他可以使用usr_function并动态地发送参数引用 – clearshot66