2017-10-09 48 views
0

我目前正在做一個自我處理的形式與5個產品,其中用戶可以輸入任何5個產品的數量。我救了他們,因爲我已經在爲功能以下打印產品展示進入需要幫助創建一個if功能

$_POST[qty_entered] 

數量:

// Print the product display 
for ($i = 0; $i < sizeof ($product_display); $i++){ 
print "<tr><td>" .$product_display[$i]['image'] . "</td>"; 
print "<td>" . $product_display[$i]['model'] . "</td>"; 
print "<td> $" . $product_display[$i]['price'] . "</td>" ; 

// Allow user inqut for quantity 

print "<td> <input type = 'text' name = 'qty_entered[]' value ='0' size = '3' maxlength = '3'> </td> </tr>";} ?> 
    </table> 

      <br><input type = 'submit' name = 'submit_button' value = 'Submit Order'><br><br> 

用戶輸入數量後,按提交按鈕,我必須檢查他們是否輸入了有效數量(這是一個正整數),然後在用戶輸入有效數量時打印發票。如果他們沒有輸入有效數量,我需要打印一條錯誤消息並且不顯示發票。下面的代碼是我現在擁有的,而且我有問題使它正確顯示。我認爲有一件事是錯誤的,那就是我需要引用保存在$ _POST ['qty_entered']中的多個數量,但是我不知道如何在不使用[0] [1] [2] [ 3],如果我使用多個,它會給我一個錯誤。 [$ i]也不起作用。

// Make sure quantity entered is a positive whole number and print table row 
     $errors = FALSE; 
if (array_key_exists ('submit_button', $_POST) && is_numeric($_POST['qty_entered'][0]) && $_POST['qty_entered'][0] > 0) { 
print "<h2>Invoice</h2> <br> <table style='border-collapse: collapse; text-align: center' 
        height='319' border='1' bordercolor='#111111' 
        cellpadding='0' cellspacing='0' width='514'> 

     <!-- create header use <th> --> 
     <tr> 
      <th>Phone</th> 
      <th>Price</th> 
      <th>Quantity</th> 
      <th>Extended Price</th> 
     </tr>"; 
} 
else { 
    $errors = TRUE; 
    Print "Please enter a valid quantity."; 
} 

請幫我創建一個合適的,如果功能檢查,如果用戶輸入有效的數量,他們按下提交鍵後。如果輸入的數量有效,請打印發票,如果沒有,則打印錯誤消息。

謝謝!

回答

0

使用的foreach:

// Start out assuming all products have quantities 
$allProductsHaveQuantities = true; 
foreach($_POST['qty_entered'] as $idx => $qty) 
{ 
    // Look for any quantities that are zero 
    if($qty == 0) 
    { 
    // One is enough, so set the flag and stop the loop 
    $allProductsHaveQuantities = false; 
    break; 
    } 
} 

// Now check the result of the flag 
if(!$allProductsHaveQuantities) 
{ 
    ...your error message here... 
} 
+0

嗨,其實產品並非所有人都擁有數量進入,有些人會爲空,如果用戶沒有輸入數量。所以我不能假設每個人都會輸入數量。我怎樣才能做到這一點? –