2014-11-01 135 views
0

我有一個像下面這樣的表單發佈到同一頁面,用戶可以動態地添加更多的文本框與jQuery。如何獲取表單輸入數組到PHP數組但不是空字段

 <h1> Add Your Order </h1> 
    <form method="post" action=""> 
     <p id="add_field"><a href="#"><span> Click to Add </span></a></p> 
     <div id="container"> 
     <input type="text" class="pid" id="' + counter + '" name="Product[]" /> 
     <input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br /> 
     </div><br /> 
     <input type= "submit" Name="submit_order" value="Submit"> 
    </form> 

一切工作正常,但如果有人添加更多的文本框,並留下一些文本框爲空,那麼它會提交。這是我的問題,我不想在我的表中提交空的文本框,我想爲此服務器端解決方案。

這裏是我完整的代碼用PHP

<body> 
    <?php 
    if (isset($_POST['submit_order'])) { 
     if (!empty($_POST['Product']) && !empty($_POST['Quantity'])) { 
      $product = ($_POST['Product']); 
      $quantity = ($_POST['Quantity']); 
      foreach ($product as $id => $value) { 
      $products = ($product[$id]); 
      $quantitys = ($quantity[$id]); 
      $query = mysql_query("INSERT iNTO myorders (product,quantity) VALUES ('$products','$quantitys')", $connection); 
      } 
     } 
    echo "<i><h2><stront>" . count($_POST['Product']) . "</strong> Entry Added </h2></i>"; 
    mysql_close(); 
    } 
    ?> 
    <?php 
    if (!isset($_POST['submit_order'])) { 
    ?> 
    <h1> Add Your Order </h1> 
    <form method="post" action=""> 
     <p id="add_field"><a href="#"><span> Click to Add </span></a></p> 
      <div id="container"> 
      <input type="text" class="pid" id="' + counter + '" name="Product[]" /> 
      <input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br /> 
      </div><br /> 
     <input type= "submit" Name="submit_order" value="Submit"> 
    </form> 
    <?php } 
    ?> 
</body> 
+0

爲什麼你不忽略空的,然後處理剩下的? – Barmar 2014-11-01 20:35:33

+0

我使用!empty()函數和進程休息,但每個字段都提交到我的表中。 – Rakesh 2014-11-01 20:40:03

+0

如果你想阻止它提交,你必須在客戶端進行。 PHP無法阻止它分發。你可以在''元素中加入'required',而現代瀏覽器則不允許它們被提交。 – Barmar 2014-11-01 20:41:20

回答

0

像這樣的東西應該工作:

foreach ($_POST[Product] as $key => $value): 
    if (empty($value)): 
     unset($_POST[Product][$key]); 
    endif; 
endforeach; 

foreach ($_POST[Quantity] as $key => $value): 
    if (empty($value)): 
     unset($_POST[Quantity][$key]); 
    endif; 
endforeach; 
1

您可以使用array_filter來獲取非空數組的元素。如果非空元素的數量與原始數組大小不同,則用戶將一些字段留空。

$filled_product = array_filter($product); 
$filled_quantity = array_filter($quantity); 
if (count($filled_product) < count($product) || count($filled_quantity) < count($quantity)) { 
    // Report error because of unfilled fields 
} 
0

謝謝大家對我的幫助,可惜沒人給我這個問題 一個完整的解決方案,但@Wranorn給我一個想法,我改變我碼和是的,這解決了我的問題

這裏是我的這個

解決方案