How can PHP be used to calculate the average of multiple grades stored in a database table?

To calculate the average of multiple grades stored in a database table using PHP, you can retrieve the grades from the database, calculate the sum of all grades, and then divide the sum by the total number of grades to get the average.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "grades";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve grades from the database
$sql = "SELECT grade FROM grades_table";
$result = $conn->query($sql);

// Calculate the sum of all grades
$total_grades = 0;
$count = 0;
while($row = $result->fetch_assoc()) {
    $total_grades += $row['grade'];
    $count++;
}

// Calculate the average
$average = $total_grades / $count;

echo "The average grade is: " . $average;

// Close the connection
$conn->close();
?>