php math question - php

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

Related

Display the total of the SUM (price * quantity) from SELECT query [duplicate]

I have a column in a table that I would like to add up and return the sum. I have a loop, but it's not working.
while ($row = mysql_fetch_assoc($result)){
$sum += $row['Value'];
}
echo $sum;
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
Using PDO (mysql_query is deprecated)
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];
Or using mysqli:
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
Try this:
$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];
Let us use the following image as an example for the data in our MySQL Database:
Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'
For this condition, the following would be the sql query and code:
$sql_qry = "SELECT SUM(duration_sec) AS count
FROM tbl_npt
WHERE date='09-10-2018' AND status='off'";
$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];
echo $total;
MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.
Method #1
$qry = "SELECT column_value AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
while ($rec = $db->fetchAssoc($res)) {
$total += $rec['count'];
}
echo "Total: " . $total . "\n";
Method #2
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #3 -SQLi
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $conn->query($sql);
$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #4: Depreciated (don't use)
$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name');
$row = mysql_fetch_assoc($res);
$sum = $row['count'];
$row['Value'] is probably a string. Try using intval($row['Value']).
Also, make sure you set $sum = 0 before the loop.
Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
$sql = "SELECT SUM(Value) FROM Codes";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
sum = $row['SUM(price)'];
}
echo sum;

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;

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

problem with calculating all elements in array

$query = $db->query("SELECT * FROM orders");
while ($row = mysql_fetch_array($query)) {
$cost= array_sum($row['cost']);
}
This is not working, I want to to calculate the sum of all elements but I get this error:
Warning: array_sum() expects parameter
1 to be array, string given in
C:\xampp\htdocs\falco\classes\controller.php
on line 303
Any idea how to calculate all the elements coming from mysql?
Thank you for your time and help.
Why not let MYSQL handle it?
$query = $db->query("SELECT orders.*,SUM(cost) as sum_cost FROM orders");
If its just a sum you want you can let the database do it for you:
Select sum(cost) from orders
Try this:
$query = $db->query("SELECT * FROM orders");
$cost = 0;
while ($row = mysql_fetch_array($query)) {
$cost += $row['cost'];
}
Or from mysql:
$query = $db->query("SELECT sum(`cost`) as `cost` FROM orders");
while ($row = mysql_fetch_array($query)) {
$cost = $row['cost'];
}
this should work:
$query = $db->query("SELECT * FROM orders");
$cost = 0;
while ($row = mysql_fetch_array($query)) {
$cost += $row['cost'];
}
or even better
$query = $db->query("SELECT SUM(cost) FROM orders");
list($cost) = mysql_fetch_row($query);
Really, it sounds like you just want the sum.
'SELECT SUM(cost) as sum_cost FROM ORDERS'

Get sum of MySQL column in PHP

I have a column in a table that I would like to add up and return the sum. I have a loop, but it's not working.
while ($row = mysql_fetch_assoc($result)){
$sum += $row['Value'];
}
echo $sum;
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
Using PDO (mysql_query is deprecated)
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];
Or using mysqli:
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
Try this:
$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];
Let us use the following image as an example for the data in our MySQL Database:
Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'
For this condition, the following would be the sql query and code:
$sql_qry = "SELECT SUM(duration_sec) AS count
FROM tbl_npt
WHERE date='09-10-2018' AND status='off'";
$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];
echo $total;
MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.
Method #1
$qry = "SELECT column_value AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
while ($rec = $db->fetchAssoc($res)) {
$total += $rec['count'];
}
echo "Total: " . $total . "\n";
Method #2
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #3 -SQLi
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $conn->query($sql);
$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #4: Depreciated (don't use)
$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name');
$row = mysql_fetch_assoc($res);
$sum = $row['count'];
$row['Value'] is probably a string. Try using intval($row['Value']).
Also, make sure you set $sum = 0 before the loop.
Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
$sql = "SELECT SUM(Value) FROM Codes";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
sum = $row['SUM(price)'];
}
echo sum;

Categories