• We just launched and are currently in beta. Join us as we build and grow the community.

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

saicle

Tech Efficiency Expert
S Rep
0
0
0
Rep
0
S Vouches
0
0
0
Vouches
0
Posts
87
Likes
146
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
Creating our 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. If you have no idea on how to import, please visit my tutorial How import .sql file to restore MySQL database.

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 average of "price" column.

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

  1. <?php
  2. //connection
  3. $conn

    =

    new

    mysqli(

    'localhost'

    ,

    'root'

    ,

    ''

    ,

    'dbtest'

    )

    ;
  4. ?>
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <meta charset="utf-8">
  9. <title>How to Get the Average of One Column in MySQL Database using PHP</title>
  10. </head>
  11. <body>

  12. <!-- displaying our table -->
  13. <table border="1">
  14. <thead>
  15. <th>ID</th>
  16. <th>Name</th>
  17. <th>Price</th>
  18. </thead>
  19. <tbody>
  20. <?php

  21. $sql

    =

    "SELECT * FROM products"

    ;
  22. $query

    =

    $conn

    ->

    query

    (

    $sql

    )

    ;

  23. while

    (

    $row

    =

    $query

    ->

    fetch_assoc

    (

    )

    )

    {
  24. echo

    "
  25. <tr>
  26. <td>"

    .

    $row

    [

    'id'

    ]

    .

    "</td>
  27. <td>"

    .

    $row

    [

    'product_name'

    ]

    .

    "</td>
  28. <td>"

    .

    $row

    [

    'product_price'

    ]

    .

    "</td>
  29. </tr>
  30. "

    ;
  31. }
  32. ?>
  33. </tbody>
  34. </table>

  35. <!-- getting the average -->
  36. <?php
  37. $sql

    =

    "SELECT AVG(product_price) AS average_price FROM products"

    ;
  38. $query1

    =

    $conn

    ->

    query

    (

    $sql

    )

    ;
  39. $row1

    =

    $query1

    ->

    fetch_assoc

    (

    )

    ;

  40. echo

    "Average Price: "

    .

    $row1

    [

    'average_price'

    ]

    ;
  41. ?>
  42. </body>
  43. </html>

That ends this tutorial. Happy Coding :)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

337,656

337,664

Top