2016-11-14 87 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注入攻擊節省開支。

相關問題