What are some best practices for efficiently calculating averages in PHP using MySQL queries?

When calculating averages in PHP using MySQL queries, it is best to utilize MySQL's built-in AVG() function to efficiently calculate the average directly in the database query. This reduces the amount of data transferred between the database and PHP, resulting in better performance.

// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Query to calculate the average of a column in a table
$query = "SELECT AVG(column_name) AS average FROM table_name";

// Execute the query
$result = mysqli_query($connection, $query);

// Fetch the result
$row = mysqli_fetch_assoc($result);

// Output the average
echo "The average is: " . $row['average'];

// Close the connection
mysqli_close($connection);