How To Get The Average Of A Column In MySQL Database Using PHP | CampCodes

How to Get the Average of a Column in MySQL Database using PHP

June 1, 2020
average in column

Creating a Database

First, we are going to create our sample database.

I’ve included a SQL file in the downloadable of this tutorial. All you have to do is import the said file.

You should be able to create a database named dbtest.

Getting the Average

Finally, we get the average of our desired column. In this tutorial, we are going to display our table data for reference, and we are going to get the percentage of the “price” column.

Create a new file, name it as index.php and paste the codes below.

    $conn = new mysqli('localhost', 'root', '', 'dbtest');
<!DOCTYPE html>
    <meta charset="utf-8">
    <title>How to Get the Average of One Column in MySQL Database using PHP</title>
<!-- displaying our table -->
<table border="1">
            $sql = "SELECT * FROM products";
            $query = $conn->query($sql);
            while($row = $query->fetch_assoc()){
                echo "
<!-- getting the average -->
    $sql = "SELECT AVG(product_price) AS average_price FROM products";
    $query1 = $conn->query($sql);
    $row1 = $query1->fetch_assoc();
    echo "Average Price: ".$row1['average_price'];

That ends this tutorial. Happy Coding!

Download Code

Leave a Reply

Your email address will not be published. Required fields are marked *