0

I am creating a PHP form that calculates the total amount of money in change, such as pennies, quarters, dimes, and nickels. The code seems to work fine until I receive an Undefined Index error in lines 29-32. Could someone please assist me with this issue and tell me what I have done wrong?

<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>
MDSL1806
  • 9
  • 1
  • 2

2 Answers2

1

This is because even before you submit the form, initially it is looking for variables $_POST['pennies'],$_POST['nickels'],$_POST['dimes'],$_POST['quarters'] and they dont exist that time. So you get

undefined index error

You can avoid this by wrapping the form submitting code inside a condition

like

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

   // code goes here

}

and name the submit button as

<input type="submit" name="btnSubmit" value="Calculate Coins" /> 
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
0

Undefined index means that one of your $_POST array items doesn't exist. For example it could be $_POST['quarters'].

You should first check if the variable exists, like so:

$quarters = $_POST['quarters'] ? $_POST['quarters']*.25 : 0;
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134