Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

calculating from a dynamic form

calculating forms math arrays



2:47 pm on Mar 25, 2009 (gmt 0)

5+ Year Member

Hello all im new to the forum and kind of new to php im trying to do this but cant figure out how

i have a page with a dynamic form wich extracts info from a table


on the form i have a repeat all which will display the title, price and id of each item, and a text box which i added id= <?php $id; ?> and also the internal name this text box will ask the user for an amount what i need to do is that this amount be multiply by the price and then do a sum of all of it, i have manage to show the amount in a $_POST[$id] but i have no idea how to do the multiplication and then the sum, i donīt need to save the data from the post in a database just show the person that is using this what he has to pay if he adds X amounts of products, i was thinking on using arrays but im still to new to php trying to learn any helps is appreciated



4:55 pm on Mar 25, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

Hi sades and welcome to the forum

Maths is fairly simple in php, for example

$answer = ( $a x $b );# multiply
$answer = ( $a - $b );# subtract
$answer = ( $a + $b );# add
$answer = ( $a / $b );# divide



5:46 pm on Mar 25, 2009 (gmt 0)

5+ Year Member

You need to save your item id, and your item amount(which the user enters) in an array. Then loop through the array, find the price for each item (using a query with the item id stored), and then multiply that with the amount - also stored in the array.


5:53 pm on Mar 25, 2009 (gmt 0)

5+ Year Member

thanks for the replays on the math part i have no problems what i dunno how to do is save the variable in the post (amount) in an arrays and then do the amount*price thing for each element of the array any tips?


6:12 pm on Mar 25, 2009 (gmt 0)

WebmasterWorld Senior Member whoisgregg is a WebmasterWorld Top Contributor of All Time 10+ Year Member

Btw, multiplication uses the asterisk "*" not the lower case "x" ;)


6:35 pm on Mar 25, 2009 (gmt 0)

5+ Year Member

<your form will probably look something like this>

<form action="index.php" method="POST">
Item1<input type="text" name="item1"><br>
Item2<input type="text" name="item2"><br>
Item3<input type="text" name="item3"><br>
<input type="submit" value="submit">

<inside your action script>

$total = 0;
foreach(array_keys($_POST) as $key){

//assigns variables
$itemId = str_replace("item", "", $key); //takes off the "item" to reveal the item id
$amount = $_POST[$key];

//checks for invalid data - i.e not integer inputs

//query for price of item
$result = mysql_query("SELECT price FROM myItemsTable where id = ".$itemId);
$row = mysql_fetch_assoc($result);
$price = $row['price'];

//total price for this item
$subTotal = $price*$amount;

//grant total


Featured Threads

Hot Threads This Week

Hot Threads This Month