2013-02-14 57 views
0

我正在创建一个PHP表单,用于计算变化中的总金额,如便士,宿舍,硬币和镍币。该代码似乎工作正常,直到我收到第29-32行中的未定义的索引错误。有人能帮助我解决这个问题,并告诉我我做错了什么吗?PHP Undefinded Index

<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> 
+1

可以显示究竟是什么错误你得到 – 2013-02-14 04:11:56

+0

使用'的print_r($ _ POST)'来看看你想说什么,而不是你期待什么。 – Passerby 2013-02-14 04:13:00

+0

但是,如果在设置数组索引之前使用之前未定义的索引错误会上升 – 2013-02-14 04:14:00

回答

0

Undefined index意味着你$_POST阵列项目中的一个不存在。例如,它可能是$_POST['quarters']

你应该先检查变量存在,就像这样:

$quarters = $_POST['quarters'] ? $_POST['quarters']*.25 : 0; 
1

这是因为您提交表单,甚至之前,最初它是寻找变量 $_POST['pennies']$_POST['nickels']$_POST['dimes']$_POST['quarters']和他们不存在那个时候。所以,你得到

未定义指数误差

您可以通过包装形式提交代码的条件内

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

    // code goes here 

} 

避免这一点,并命名提交按钮

<input type="submit" name="btnSubmit" value="Calculate Coins" />