Multiply column values from multiple rows and then add - php

I need to get the price and amount sold from a database, and then multiply them together to get an output for each one, and then add them all together. I think I could use a foreach loop, but I'm not sure if the variable would retain it's value for each time it goes through. This is what I've tried so far:
$query = "SELECT * FROM `inv`";
$data = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($data)){
if(isset($fin2)){
$fin = $fin2;
} else {
$price = str_replace('$', '', $row['price']);
$fin2 = ($row['sold'] * $price + $fin);
}
if(isset($fin)){
$fin = ($fin + $fin2);
echo $fin;
}
As you can see, I'm kind of confused, and any help would be appreciated.

Why not do the calculation in the database?
SELECT SUM(price * sold) as total
FROM `inv`;
EDIT:
SELECT SUM((replace(price, '$', '') + 0) * sold) as total
FROM `inv`;

Related

How to calculate the sum of number array elements from multiple database rows using php?

I need to count the number of elements that exist in the column of a MySQL database row for multiple rows and them add them all together. This is the code I used to count the number of array elements (which are numbers separated by commas):
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
But now I need to do this for each row, which could vary depending on the query. I need to add the $result of each row together to get a final sum of all the rows. I used the following code but I get the incorrect value, can someone please point me in the right direction?
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
foreach ($count_fetch as $row) {
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
$end_result += $result;
}
echo $end_result;
You are just fetching 1 row and then trying to count over that row, instead you need to loop over the rows and add the fields in that...
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$end_result = 0;
$count_query = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_assoc($count_query)) {
$end_result += substr_count($row['micro_analysis'], ",") + 1;
}
echo $end_result;
Replace your code with the following:
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
$end_result=0;//initialize variable to 0
foreach ($count_fetch as $k => $row) {
if($k == 'micro_analysis'){
$result = substr_count($row, ",") + 1; //change over here
$end_result += $result;
}
}
echo $end_result;

how to sum values of total column, i.e calculate the sub total? as total is not from database

enter image description here*now how can i calculate the sub total of the (tolal) field values these values are not from database, these are from (price of item * quantity)*
This is my code:
<?php
$ipAdd = getRealIpAddr();
$checkPrice= "select * from cart where ipAdd= '$ipAdd' ";
$run= mysqli_query($conn,$checkPrice);
while($record= mysqli_fetch_array($run)){
$proId= $record['pId'];
$cId= $record['cId'];
$cQuant= $record['qnty'];
$proPric= "select * from products where prodId= '$proId' ";
$runPrice=mysqli_query($conn, $proPric);
while($pPrice=mysqli_fetch_array($runPrice)){
$proPri= $pPrice['prodPrice'];
$t = $proPri* $cQuant ;
}
}
?>
Alrighty, so assuming you want total of all items times all the quantities, here's what you do:
$ipAdd = getRealIpAddr();
$total = 0;
$checkPrice = "SELECT * FROM cart WHERE ipAdd = '$ipAdd' ";
$run = mysqli_query($conn,$checkPrice);
while($record = mysqli_fetch_array($run)){
$proId = $record['pId'];
$cId = $record['cId'];
$cQuant = $record['qnty'];
$proPric = "SELECT * FROM products WHERE prodId = '$proId' ";
$runPrice = mysqli_query($conn, $proPric);
$pPrice = mysqli_fetch_array($runPrice);
$proPri = $pPrice['prodPrice'];
$t = $proPri * $cQuant ;
$total += $t;
}
echo $total; // will be a sum of all prices times all quantities
You don't need while if you're fetching just one value, literally just removing it works fine
You start this process by declaring $total variable, in this case resetting it
You do everything you already did, after which you increment $total by whatever is the value of $t
Keep in mind that $total will change during this while loop, so considering this looks like a per-user-query, make sure to use it outside of the loop.

Loop through results from mysql, and sum values

I use a while loop to process table record like this:
$get_s = "SELECT * FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
while ($show_s = mysqli_fetch_assoc($result)) {
$quantity = $show_s['sells_quantity'];
}
mysqli_free_result($result);
}
I have all my table records, and now I want to sum up all quantity fields , but I don't know how to do it.
For example, if I got 10 records quantity for records like 2, 1, 5, 1, 3, 6 etc, I would like to sum them like this: 2+1+5+1+3+6 = 18
If you can do something in mysql - do it. Use SUM aggregation function:
$get_s = "SELECT SUM(sells_quantity) as sells_sum FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
$show_s = mysqli_fetch_assoc($result);
echo $show_s['sells_sum'];
}
mysqli_free_result($result);
Still, if you need certain values of rows - you can count sum in a loop:
$get_s = "SELECT * FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
$total = 0;
while ($show_s = mysqli_fetch_assoc($result)) {
$quantity = $show_s['sells_quantity'];
$total += $quantity;
}
mysqli_free_result($result);
echo $total;
}
But mysql SUM() is preferrable.

Getting a percentage of one PHP variable from another

I am trying to get a percentage of a php variable from another, for example i have two databases of information, the first database is full of unidentified information. The second database is full of the information we have identified. and so i want to work out dynamically the percentage of the total information identified.
Below is a php function to work out a percentage,
//TOTAL ENTRIES INTO Table 1 FOR total data
$result = mysql_query( "SELECT * FROM table1" );
$num_total = mysql_num_rows( $result );
//TOTAL ENTRIES IN Table 2 FOR THE PERCENTAGE
$result = mysql_query( "SELECT * FROM table2" );
$num_amount = mysql_num_rows( $result );
function percent($num_amount, $num_total) {
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count3 = 100 - $count2;
$count = number_format($count3, 0);
echo $count;
}
Both queries return the correct information of the total number of rows counted in the database, however the count variable does not return any information.
Any ideas or suggestions would be appreciated.
Thanks
Stan
You echo the result, but you do not return it from the function. That is probably the problem.
However, you can do the percentage calculation all in SQL:
SELECT 100*( SELECT COUNT(*) FROM table1 ) / ( SELECT COUNT(*) FROM table2 )
AS percent;
Otherwise,
function percent($num, $total)
{
return number_format((100.0*$num)/$total, 2);
}
My guess is that something like this should probably work (mind you, I have not tested this, so it probably needs tweaking):
<?php
//TOTAL ENTRIES INTO Table 1 FOR total data
$result = mysql_query("SELECT COUNT(*) AS total FROM table1");
$table1_total = mysql_result($result, 0);
//TOTAL ENTRIES IN Table 2 FOR THE PERCENTAGE
$result2 = mysql_query("SELECT COUNT(*) AS total FROM table2");
$table2_total = mysql_result($result2, 0);
function percent($num_amount, $num_total) {
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count3 = 100 - $count2;
$count = number_format($count3, 0);
echo $count;
}
percent($table1_total, $table2_total);
Try this:
<?php
function percent($num_amount, $num_total) {
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = number_format($count2, 0);
echo $count2."<br>";
}
percent(50,100);
percent(13,100);
percent(13,200);
?>

php math question

I have a db table which have a row of a product amount. I want to create a loop that will calculate for me the sum for all the amounts.
$results = mysql_query("SELECT *
FROM prod");
while($info = mysql_fetch_array($results)) {
$amount = $info['amount'];
}
amount is the var for each product cost. I want to get a sum for all the vars together - how can I do it?
Use the SUM() function in a SQL query.
$result = mysql_query("SELECT SUM(amount) AS sum_amount FROM prod");
if ( $result )
$sum = mysql_result($result, 0, 0);
Easier to do in MySQL:
SELECT SUM(amount) FROM prod
Then fetch the result.
First:
You can do this with mysql
SELECT SUM(amount) FROM ....
Second:
while ($info = mysql_fetch_array($results)) {
$amount[] = $info['amount'];
}
$sum = array_sum($amount);
You can add the amounts to a variable:
$results = mysql_query("select * from prod");
$sum = 0
while($info = mysql_fetch_array($results)) {
$amount = $info['amount'];
$sum += $amount
}
Or you can do it in SQL:
SELECT SUM(column) FROM table

Categories