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();
?>
Keywords
Related Questions
- What potential pitfalls should be considered when trying to compare different date formats in PHP, such as "j.n.y" and timestamps?
- How can PHP developers ensure the security and integrity of data when interacting with databases?
- What are some best practices for handling session management in PHP to ensure accurate countdown functionality?