How to Display Average Of All Rows In Column of PHP MySQL?

03-Apr-2023

.

Admin

How to Display Average Of All Rows In Column of PHP MySQL?

Hi Dev,

If you need to see example of how to display average of all rows of a column in php mysql. this example will help you mysql avg() function. you can see display average of data from database in php mysql. you'll learn average sql mysql avg tutorial. You just need to some step to done calculate get the average in php mysql.

In this article, we show how to get the average of all rows of a column of a MySQL table using PHP.

Example :


index.php

$sql = CREATE TABLE sales (

product varchar(255),

order_date date,

sale int

);

Insert some records in the table using insert command :

$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Laptop', '2022-11-01', 20);

$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Mobile', '2022-10-10', 25);

$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Mobile', '2022-08-12', 15);

$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Laptop', '2022-08-12', 30);

$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Laptop', '2022-07-18', 20);

Display all records from the table using select statement :

select * from sales;

Output:

+---------+------------+------+

| product | order_date | sale |

+---------+------------+------+

| Laptop | 2022-11-01 | 20 |

| Mobile | 2022-10-10 | 25 |

| Mobile | 2022-08-12 | 15 |

| Laptop | 2022-08-12 | 30 |

| Laptop | 2022-07-18 | 20 |

+---------+------------+------+

If you want to calculate average sales per day for each product, then here’s an SQL query for it.

SELECT product, avg(sale) FROM sales by product;

Output:

+---------+-----------+

| product | avg(sale) |

+---------+-----------+

| Laptop | 23.3333 |

| Mobile | 20.0000 |

+---------+-----------+

I hope it could help you...

#PHP