2017-10-09 41 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

嗨,其实产品并非所有人都拥有数量进入,有些人会为空,如果用户没有输入数量。所以我不能假设每个人都会输入数量。我怎样才能做到这一点? –