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...
- How to Increase max_connections in MySQL?
- How to Install the PHP PDO MySQL Extension on Ubuntu 22.04?
- How to Install PHP MySQL on Linux Ubuntu?
- How to Install LEMP Stack Nginx, MySQL, PHP on Ubuntu?
- How to Change MySQL Root User Password Ubuntu?
- PHP 8 MySQL Form Validation Example
- How to Select First Row Only in PHP MySQL?
- How To Backup MySQL Database Using PHP Example