Php sum value once when loop start - php

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;
}
?>

Related

php mysqli event get by date

I have made a code where I get all nubers in the month then I am adding on events from my database. I need the numbers to come from the database in $sqldates I am now only getting array as when I echo the $sqldates. I have 4, 10, 22 and 26 in my database now.
This is what I am getting now look at the picture
enter image description here
This is the result I want look at this picture.
enter image description here
How do I get the results from my database as picture 2 shows? Pleas help how to get the numbers from array.
<table>
<?php
//database connent
include 'con.php';
//get day from event
$sql = "SELECT day, color FROM events";
$result = mysqli_query($con, $sql);
$sqldates = array(array('day', 'color_value'), array('date_value', 'color_value'), array('date_value', color_value));
while($row=mysqli_fetch_array($result)){
array_push($sqldates, $row['day'], $row['color'] );
echo $row['day'];
}
$counter = 0;
//first day
$firstday = '1';
$two = cal_days_in_month(CAL_GREGORIAN, 8, 2018); // 31
//for loop get all day in month
for ($number = $firstday; $number <= $two; $number++)
if (in_array($number , $sqldates)) {
echo "<td width=50 bgcolor='#{$sqldates[$counter][1]}'>$sqldates[$counter][0]</td>";
$counter++;
} else {
echo"<td width=50 bgcolor='#1e8e8e'>$number</td>";
}
?>
</table>
For your updated question this should be good guide:
<table>
<?php
//database connect
include 'con.php';
//get day from event
$sql = "SELECT day, color FROM events";
$result = mysqli_query($con, $sql);
$sqldates = array();
$colors = array();
while($row=mysqli_fetch_array($result)){
array_push($sqldates, $row['day']);
array_push($colors, $row['color']);
}
//first day
$firstday = '1';
$two = cal_days_in_month(CAL_GREGORIAN, 8, 2018); // 31
//for loop get all day in month
$counter = 0;
for ($number = $firstday; $number <= $two; $number++)
if (in_array($number , $sqldates)) {
echo "<td width=50 bgcolor='$colors[$counter]'>$sqldates[$counter]</td>";
$counter++;
} else {
echo"<td width=50 bgcolor='#1e8e8e'>$number</td>";
}
?>
</table>
Note that you need to have defined color for each day, otherwise you will get "Undefined offset" notice.
You are trying to echo an array. Instead you should echo a value from that array with specified index. If I am not wrong, this should work:
//first day
$firstday = '1';
$two = cal_days_in_month(CAL_GREGORIAN, 8, 2018); // 31
//for loop get all day in month
$counter = 0;
for ($number = $firstday; $number <= $two; $number++)
if (in_array($number , $sqldates)) {
echo"<td width=50 bgcolor='#f44242'>$sqldates[$counter]</td>";
$counter++;
} else {
echo"<td width=50 bgcolor='#1e8e8e'>$number</td>";
}

PHP sum each loop value

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.

How to show subtraction value using php loop?

For example :
$monthly_bill = 700
$paid_amount = 2100
Now I want to use a php loop which will print me 700, 700 and 400 to each line. How can I do this ?
I am doing following code but not working :
<?php
$paid_amount = 1800;
$monthly_bill = 700;
$counting_month = round($paid_amount / $monthly_bill);
for ($x=1; $x<=$counting_month; $x++) {
echo $insert = $paid_amount - $monthly_bill;
$paid_amount = $insert;
echo '<br/>';
}
Don't use for loop. Those run a fixed number of times, and your loop would keep running until well after the money runs out.
Use a do instead, and have its termination clause be when the money runs out:
$remaining = 1800;
$monthly = 700;
do {
echo $monthly;
$remaining -= $monthly;
if ($remaining < $monthly) {
$monthly = $remaining;
}
} while ($remaining > 0);
<?php
$amount = 1800;
$monthlybill = 700;
for ($i=0; $i<$amount/$monthlybill; $i++) {
echo "paid for " . ($i+1) . " month =" . $monthlybill . "<br>\n";
$amount -= $monthlybill;
}
if ($amount>0) {
echo "paid for " . ($i+1) . " month =" . $amount;
}

PHP order submission total calculate

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>

How to get max value in loop

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)

Categories