2016-11-14 133 views
1

我正在创建一个数据库系统来存放和检索零售商/公司的发票。我正在寻找一种方法来通过php表单添加多个条目到mysql数据库,而无需单独添加每个项目。我的表单看起来像;通过php表格添加多个条目到mysql数据库

<div class="new_invoice"> 
<form action="addCustomerInvoice.php" method = "post" enctype= "multipart/form-data"> 
<fieldset> 
<legend> Add new invoice for <?php echo $rsCustomer['forename']; echo ' '; echo $rsCustomer['surname']; ?></legend> 
<h4>Invoice Number:</h4> 
<input type="text" name="invoice_no"> 
<h4>Item Quantity:</h4> 
<input type="text" name="quantity"> 
<h4>Item Name:</h4> 
<input type="text" name="item_name"> 
<h4>Item Category:</h4> 
<input type="text" name="item_category"> 
<h4>Manufacturer:</h4> 
<input type="text" name="item_manufacturer"> 
<h4>Item Description:</h4> 
<input type="text" name="item_description"> 
<h4>Item Price:</h4> 
<input type="text" name="item_price"> 
<h4>Item Information:</h4> 
<input type="text" name="item_info"> 
<input type="submit" value="Add new record"> 
</fieldset> 
</form> 
</div> 

和过程一样;

<?php 
          include 'database_conn.php'; 
           $InvoiceNumber = $_POST['invoice_no']; 
           $Quantity = $_POST['quantity']; 
           $ItemName = $_POST['item_name']; 
           $ItemCat = $_POST['item_category']; 
           $ItemMan = $_POST['item_manufacturer']; 
           $ItemDesc = $_POST['item_description']; 
           $ItemInfo = $_POST['item_info']; 
          $sql = "INSERT INTO hlinvoicetable (invoice_no, quantity, item_name, item_category, item_manufacturer, item_description, item_info) VALUES ('$InvoiceNo', '$Quantity', '$ItemName', '$ItemCat', '$ItemMan', '$ItemDesc', '$ItemInfo')"; 
           $queryresult = mysqli_query($conn,$sql) or die(mysqli_error()); 
          echo "New invoice added. 

          mysqli_close($conn); 
          ?> 

我想知道有没有办法重复的形式,并有一个新的记录,除非字段为空,因此它被忽略,没有添加行添加到数据库?也可以添加所有项目保持相同的主键(invoice_no)?

在此先感谢!

+0

如果我不这样说,别人会:不要插入unsanitized数据。在[bobby-tables.com](http://bobby-tables.com/)查看PHP的安全代码实践。 (在mysqli的情况下,使用准备好的语句。) –

+0

你是对的我只是想剥离代码,尽量保持它尽可能简单,但你的建议很好! –

回答

0

您需要在输入上使用数组名称。例如:

<input type="text" name="invoice_no[]"> 
... 
<input type="text" name="invoice_no[]"> 

然后在PHP中,你会从$_POST['invoice_no'][0]$_POST['invoice_no'][1]获得值等

你可以遍历所有的值,如:如上所述

foreach ($_POST['invoice_no'] as $key => $invoice) { 
    if (!empty($_POST['invoice_no'][$key]) 
     && !empty($_POST['quantity'][$key]) 
     && !empty($_POST['item_name'][$key]) 
     //... include all fields that can't be left empty 
    ) { 
     // Do insert 
    } 
} 

而且, ,请确保使用绑定参数,而不是将用户提供的数据直接放入SQL查询中。它实际上并不需要太多额外的代码,并且有必要为SQL注入攻击节省开支。

相关问题