Calculate average and sum from Mysql query

The AVG function return the average value of the specified column. For example I have a table of product list and now I want the total of price and average price of all the products.

id name price
43245 Jeans 19.99
43246 Top 3.99
43247 Playstation 89.95
43248 Men’s T-Shirt 32.50
43249 Shirt 34.97
43250 Laptop 3.99
43251 Mobile 21.55
43252 Lemon 8.73

Code:

PHP code to find out the total price and average price is

<?php

$query = “SELECT¬†AVG(price)as priceavg, SUM(`price`) as pricesum FROM products”;

$result = mysql_query($query);

$row = mysql_fetch_array($result);

echo “The Total price of products is “. $row[‘pricesum’];

echo “<br />”;

echo “The Average price of products is “. $row[‘priceavg’];

?>

Output:

The Total price of products is 21.67

The Average price of products is 26.96

Share This Post

Post Comment