0

我正在创建一个 PHP 表单,用于计算找零的总金额,例如便士、25 美分、硬币和镍币。代码似乎可以正常工作,直到我在第 29-32 行收到未定义索引错误。有人可以帮我解决这个问题并告诉我我做错了什么吗?

<head> 
<title>Fill in the form and I will show the greeting. </title>
<style type="text/css">
h1 {font-family:'Times New Roman'; }
</style>

<body bgcolor="orange">  
<form action="Lab6-1.php" method="post" >
<h1>Please enter your coin count and denominations.</h1>
<p>
<h1>Pennies (1 cent):
   <input type="text" size="16" maxlength="20" name="pennies" value="<?php echo $_POST['pennies']?>"/></h1>

<h1>Nickels (5 cents):
    <input type="text" size="16" maxlength="20" name="nickels" value="<?php echo $_POST['nickels']?>"/></h1> 

<h1>Dimes (10 cents):  
    <input type="text" size="16" maxlength="20" name= "dimes" value="<?php echo $_POST['dimes']?>"/></h1>
<h1> Quarters (25 cents):
    <input type="text" size="16" maxlength="20" name= "quarters" value="<?php echo $_POST['quarters']?>"/></h1>
<br /><br />
<input type="submit" value="Calculate Coins" />
<input type="reset" value ="Clear Form" />

<?php
   $pennies = $_POST['pennies']*.01;
   $nickels = $_POST['nickels']*.05;
   $dimes = $_POST['dimes']*.10;
   $quarters = $_POST['quarters']*.25;

   $total = $pennies + $nickels + $dimes + $quarters;

   $money = array ( "Quarters" => $quarters, "Dimes"=> $dimes, "Nickels" => $nickels, "Pennies" => $pennies, "Total" => $total);

   echo "<table border = \"1\" >";


 foreach ( $money as $key => $value ) {
 print("<tr><td> $key </td><td> $value</td> </tr>");  
  } 
 echo "</table>";
?>

</p>
</form>
</body>
</html>
4

2 回答 2

1

这是因为即使在您提交表单之前,它最初也在寻找变量 $_POST['pennies'], $_POST['nickels'], $_POST['dimes']$_POST['quarters']而那时它们并不存在。所以你得到

未定义的索引错误

您可以通过将表单提交代码包装在条件中来避免这种情况

喜欢

if(isset($_POST['btnSubmit'])) }{

   // code goes here

}

并将提交按钮命名为

<input type="submit" name="btnSubmit" value="Calculate Coins" /> 
于 2013-02-14T04:17:11.507 回答
0

Undefined index表示您的$_POST数组项之一不存在。例如,它可能是$_POST['quarters'].

您应该首先检查变量是否存在,如下所示:

$quarters = $_POST['quarters'] ? $_POST['quarters']*.25 : 0;
于 2013-02-14T04:13:09.673 回答