Simple Auto Calculate Function

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
landzir101
Forum Newbie
Posts: 3
Joined: Fri Apr 22, 2011 4:43 pm

Simple Auto Calculate Function

Post by landzir101 »

I was looking to create a simple cart function off of PHP that multiples one fixed number and one variable (based on user input). So, basically the user enters 5 into the 'quantity' box and since there is only one item costing $20 it would automatically recalculate to $100 and show that in a 'total' box. I would appreciate any resources to help guide and show me more in-depth about it. Below I have provided my code, which is simple and I am sure not really close at all to what the final product needs to be.

Code: Select all

<html>
<body>
<form action="myform.php" method="post">
<p>Quantity: <input type="text" size=3 name="quantity" /></p>
</form>

</body>
</html>

<?php

$first_number = $quantity;
$second_number = 20;
$sum_total = $second_number * $first_number;

print ($sum_total);

?>
danwguy
Forum Contributor
Posts: 256
Joined: Wed Nov 17, 2010 1:09 pm
Location: San Diego, CA

Re: Simple Auto Calculate Function

Post by danwguy »

I would do something like this
form.php:

Code: Select all

<form method="post" action="">
Quantity: <input type="text" name="quantity" />
<input type="Submit" name="update" value="update" />
</form>
<?php
if(isset($_POST['update'])) {
    $num = $_POST['quantity'];
     $price = '20';
$total = (int)($num * $price);
echo "Total price is: " .$total;
Post Reply