Need Help adding up prices.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
stylus
Forum Newbie
Posts: 17
Joined: Fri Dec 16, 2005 9:22 am

Need Help adding up prices.

Post by stylus »

Hello,

I am trying to figure out how to add up the total cost of my accessories, and assign it to the value of $total_accessory_cost. Then add that cost with 2 other values. I can add the other two no problem, because they are just plain input box's. The accessories are different because they are in an array, and I don't know how to have it say add up $price_$i then assign it to a value.

here is my code that submits the information:

Code: Select all

<?PHP 
      $field_count = $_POST['field_count'];
            for($i= 1;$i <= $field_count;++$i) 
	{ 
	   echo "
      				
			<tr>
                           <td align=left width=90><input type=text size=10 name=\"model_$i\" value=\"".$_POST['model_'.$i]."\"></td>
                           <td align=left width=90><input type=text size=40 name=\"description_$i\" value=\"".$_POST['description_'.$i]."\"></td>
                           <td align=right>$<input type=text size=10 name=\"price_$i\" value=\"".$_POST['price_'.$i]."\"></td>
	       </tr> ";
	};
?>

On the next page I only have this so far because I don't even know where to start with the accessories.

Code: Select all

<?PHP 
  
            $total_equipment_cost = $_POST['machine_base_price'] + $_POST['surge_price']  + $total_accessory_cost ;	
  
  ?>
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Your design isn't too good for handling this... you could actually make you name fields arrays on the form (name="foo[]").

Code: Select all

for ($i=0; $i<count($_POST['model']); $i++)
{
    echo "
    <tr>
        <td align=left width=90><input type=text size=10 name=\"model[$i]\" value=\"$_POST[model][$i]\"></td>
        <td align=left width=90><input type=text size=40 name=\"description[$i]\" value=\"$_POST[description][$i]\"></td>
        <td align=right><input type=text size=10 name=\"price[$i]\" value=\"$_POST[price][$i]\"></td>
    </tr>";
}

Code: Select all

$total_accessory_cost = array_sum($_POST['price']);
$total_equipment_cost = $_POST['machine_base_price'] + $_POST['surge_price']  + $total_accessory_cost;
I haven't tested that but you see the idea :)
stylus
Forum Newbie
Posts: 17
Joined: Fri Dec 16, 2005 9:22 am

Post by stylus »

Thanks,

I always appreciate when somebody can look at my code and say thats the rookie way of doing it, here is something that will work better. I had to make a few edits, but your code worked very well.

Thanks Again.
Post Reply