I made an order form using PHP that makes subtotals for each item ordered. How can I make a function/code to display the total for the order in the bottom of the page. I tried to read on PHP.net but couldn't figure it out.
Here is a sample of my code:
$bread = $_POST["bread"];
$cheese = $_POST["cheese"];
$eggs = $_POST["eggs"];
$priceBread = 5;
$priceCheese = 5;
$priceEggs = 3.6;
function subtotal($incomingQuantity, $incomingPrice){
return $incomingQuantity * $incomingPrice;
}
<div id="breadSubtotal">$<?php echo subtotal($bread, $priceBread); ?>
<div id="cheeseSubtotal">$<?php echo subtotal($cheese, $priceCheese); ?></div>
<div id="eggsSubtotal">$<?php echo subtotal($eggs, $priceEggs); ?></div>
I want the total from the subtotals of all the items
something like this?
$total = 0;
function subtotal($incomingQuantity, $incomingPrice){
global $total;
$sub = $incomingQuantity * $incomingPrice;
$total += $sub;
return $sub;
}
then in the HTML
<div id="total">$<?php echo $total; ?></div>
also, dont forget to make safe your incoming $_POST vars with something like
$bread = htmlspecialchars($_POST["bread"]);
I want the total from the subtotals of all the items
Its really simple to calculate. Try like this
$bread = 2;
$cheese = 3;
$eggs = 4;
$priceBread = 5;
$priceCheese = 5;
$priceEggs = 3.6;
$total = 0;
function subtotal($incomingQuantity, $incomingPrice){
return $incomingQuantity * $incomingPrice;
}
$total += subtotal($bread, $priceBread) ;
$total += subtotal($bread, $priceBread);
$total += subtotal($cheese, $priceCheese);
echo "order total : " + $total;
If am not wrong, you want to calculate the number of each item with the price of the items. So based on that this is how I would do it.
public function getTotal()
{
$total = 0;
$subTotal = func_get_args();
for($a = 0; $a < sizeof($subTotal); $a++)
{
$total += $subTotal[$a];
}
return $total;
}
Test the function
getTotal(subtotal($bread, $priceBread), subtotal($cheese, $priceCheese), subtotal($eggs, $priceEggs));
That's how I would do it, gives you more flexibility
<?php
$bread = $_POST["bread"];
$cheese = $_POST["cheese"];
$eggs = $_POST["eggs"];
//prices
$prices = array('bread'=>5,'cheese'=>5,'eggs'=>3.6);
function calculateOrderTotals($items, $prices){
//result
$result = array('total'=>0, 'subTotal'=>array());
//total
$total = 0;
//calculate subtotal and total
foreach ($items as $item => $nPurchased){
$subTotal = $nPurchased* $prices[$item];
$result['subTotal'][$item] = $subTotal;
$total += $subTotal;
}
//set total
$result['total'] = $total;
//return
return $result;
}
//call function to calculate
$totals = calculateOrderTotals(array('bread'=>$bread,'cheese'=>$cheese,'eggs'=>$eggs), $prices);
?>
<div id="breadSubtotal"><?php echo $totals['subTotal']['bread'];?>
<div id="cheeseSubtotal"><?php echo $totals['subTotal']['cheese']; ?></div>
<div id="eggsSubtotal"><?php echo $totals['subTotal']['eggs']; ?></div>
<div id="total"><?php echo $totals['total']; ?></div>
Related
I wanted to make a simple calculations to summarized what I purchased.
Using $_GET every time the value is updated it should save in an array then when 'start' is executed, it gives the sum. Sorry the codes here are just googled and I'm not really a programmer. I don't know how to combine the two sets of code (array + sum).
$number = $_GET ['input'];
$arr = array ($number);
$data = array($arr);
foreach ($tareas as $tarea) {
$data[] = $tarea;
}
var_dump($data);
$sum = 0;
foreach($group as $key=>$arr) {
$sum+= $arr;
}
echo $sum;
So I got this code from withinweb.com and modified to make it simpler.
<?php session_start();
$products = array($_GET["prod"]);
$amounts = array($_GET ["cost"]);
if ( !isset($_SESSION["total"]) ) {
$_SESSION["total"] = 0;
for ($i=0; $i< count($products); $i++) {
// $_SESSION["qty"][$i] = 0;
$_SESSION["amounts"][$i] = 0;
}
}
//---------------------------
//Reset
if ( isset($_GET['reset']) )
{
if ($_GET["reset"] == 'true')
{
unset($_SESSION["qty"]); //The quantity for each product
unset($_SESSION["amounts"]); //The amount from each product
unset($_SESSION["total"]); //The total cost
unset($_SESSION["cart"]); //Which item has been chosen
}
}
//---------------------------
//Add
if ( isset($_GET["add"]) )
{
$i = $_GET["add"];
$qty = $_SESSION["qty"][$i] + 1;
$_SESSION["amounts"][$i] = $amounts[$i] * $qty;
$_SESSION["cart"][$i] = $i;
$_SESSION["qty"][$i] = $qty;
}
//---------------------------
//Delete
if ( isset($_GET["delete"]) )
{
$i = $_GET["delete"];
$qty = $_SESSION["qty"][$i];
$qty--;
$_SESSION["qty"][$i] = $qty;
//remove item if quantity is zero
if ($qty == 0) {
$_SESSION["amounts"][$i] = 0;
unset($_SESSION["cart"][$i]);
}
else
{
$_SESSION["amounts"][$i] = $amounts[$i] * $qty;
}
}
//cart
if ( isset($_SESSION["cart"]) ) {
$total = 0;
foreach ( $_SESSION["cart"] as $i ) {
echo '' . $products[$_SESSION["cart"][$i]] . ' - ' . $_SESSION["amounts"][$i] . '<br>';
$total = $total + $_SESSION["amounts"][$i];
}
$_SESSION["total"] = $total;
echo'
<br>
Total : ' . $total . '
';
}
?>
When I input ?add=0&prod=apple&cost=100, it gives me:
apple - 100
Total : 100
But when I add another session, ?add=1&prod=orange&cost=200 it doesn't give the right answer.
orange - 100
- 0
Total : 100
It should return me this value, I'm puzzled where could be the error.
apple - 100
orange - 200
Total : 300
Yes, I'm not a coder, but trying to solve a big problem.. :) Thanks for those who help.
Hi I have a value in variable i want to add this value first time when loop start not always. for example
<?php
$balance = 100;
while($row = mysql_fetch_array($query)
{
echo $row['amount'] + $balance; // for example $row['amount'] is 50, 20 , 30;
}
?>
i want result as follow
<?php
150
170
200
?>
Sample Code..
$balance = 100;
$counter=1;
$total=0;
while($row = mysql_fetch_array($query)
{
if($counter==1)
{
$total=$row['amount'] + $balance; // for example $row['amount'] is 50, 20 , 30;
}
else
{
$total = $row['amount']+$total;
}
echo $total.'<br>';
$counter++;
}
the most simple way to do so
<?php
$balance = 100;
while($row = mysql_fetch_array($query)
{
$balance = $balance + $row['amount'];
echo $balance;
}
?>
I am writing a bit of php code to output a random value
$max_mal = (3 - $oray);
$oray = 1;
$max = 100;
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
and for each loop goes here
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
I am looking to get decimal values upto 5 numbers, but once a negative value comes it results out as 0.000-1 instead of -0.00001
$myresultb = str_pad($mario, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
$total_score = 300;
echo $myresultf;
Secondly I am new to php learning so am I doing this PHP correct or it needs improvement
I have a div to show total score like this
<div id="total_score"></div>
and another div to show current score which value comes as echo $myresultf;
<div id="current_score"></div>
I want to update total score in real time with jquery wheneven button is clicked and <?php echo $myresultf ?> is refreshed in real time also
$("#play").click(function() {
var currentscore = $("#current_score").val();
var totalscore = $("#total_score").val();
how to do this.....
});
Try this:
$max = 100;
$oray = 1;
$max_mal = (3 - $oray);
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
$negative_var=false;
if($myresult < 0)
{
$negative_var=true;
$myresult = 0-$myresult;
}
$myresultb = str_pad($myresult, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
if($negative_var)
$myresultf="-".$myresultf;
$total_score = 300;
echo $myresultf;
simple use as follow:
$myresultb =str_replace('-','',$myresultb);
if($myresult == -1) {
$myresultf = '-0.'.$myresultb.'<br/>';
}
else {
$myresultf = '0.' . $myresultb . '<br/>';
}
I have a problem with my addition :
So I have this code :
$total = 0;
foreach(getHistory($this->id) as $history){
$aHistoryFilter['date'] = $history['date'];
$aHistoryFilter['ls'] = $history['ls']);
$aHistoryFilter['montant'] = $history['montant'];
$aHistoryFilter['total_montant'] = $total+$history['montant'];
$aHistory[] = $aHistoryFilter;
}
return $aHistory;
So I want to save in total_montant the last value, but not work and I don't understand why...Can you help me please ? Thx in advance
You should also do:
$total = $total + $history['montant'];
otherwise you do not add anything (since $total=0;)
So you get:
foreach(getHistory($this->id) as $history){
$aHistoryFilter['date'] = $history['date'];
$aHistoryFilter['ls'] = $history['ls']);
$aHistoryFilter['montant'] = $history['montant'];
$aHistoryFilter['total_montant'] = $total+$history['montant'];
$total = $total + $history['montant'];
$aHistory[] = $aHistoryFilter;
}
update your code to be:
$total = 0;
foreach(getHistory($this->id) as $history){
$aHistoryFilter['date'] = $history['date'];
$aHistoryFilter['ls'] = $history['ls']);
$aHistoryFilter['montant'] = $history['montant'];
$total = $total+$history['montant'];
$aHistory[] = $aHistoryFilter;
}
$aHistoryFilter['total_montant'] = $total ;
because in your code you $history['montant'] to $total but you didn't assign the result to $total
Try this:
$total = 0;
foreach(getHistory($this->id) as $history){
$aHistoryFilter['date'] = $history['date'];
$aHistoryFilter['ls'] = $history['ls']);
$aHistoryFilter['montant'] = $history['montant'];
// this adds the $history['montant'] to the $total
$total += $history['montant'];
// this adds the $total to your variable
$aHistoryFilter['total_montant'] = $total;
$aHistory[] = $aHistoryFilter;
}
return $aHistory;
ok so im working with this loop and getting information from DB:
for($i0 = 0; $i0 < $total0; $i0 ++) {
$id = $oconecta->retrieve_value($i0, "id_tam_product");
$price = $oconecta->retrieve_value($i0, "price_tam_product");
echo $id; // RESULTS: 312, 313, 314
echo $price; // RESULTS: 180.00, 250.00, 300.00
}
i was wondering how can i get the MAX value for that loop:
echo $id; //RESULTS: 314
echo $price; //RESULTS: 300.00
$maxID = 0;
$maxPrice = 0;
for($i0=0;$i0<$total0;$i0++)
{
$id=$oconecta->retrieve_value($i0,"id_tam_product");
$price=$oconecta->retrieve_value($i0,"price_tam_product");
$maxID = max($id, $maxID);
$maxPrice = max($price, $maxPrice);
}
echo "MAX ID: $maxID - Max PRICE: $maxPrice";
Use the max() function to determine the highest number of a set.
Either you use SQL's MAX() if you can modify your SQL query, or keep the max value in a variable in each loop, and reassign it everytime:
$firstLoop = true;
$maxId = 0;
$maxPrice = 0;
for ($i0 = 0; $i0 < $total0; $i0++)
{
$id = $oconecta->retrieve_value($i0, "id_tam_product");
$price = $oconecta->retrieve_value($i0, "price_tam_product");
if ($firstLoop) {
$firstLoop = false;
$maxId = $id;
$maxPrice = $price;
}
else {
$maxId = max($maxId, $id);
$maxPrice = max($maxPrice, $price);
}
}
(the boolean is here if you have negative values it wouldn't work if $maxPrice and $maxId are initiliazed with 0)