What are some best practices for handling and displaying data from a MySQL database in PHP using timestamps and averages?

When handling and displaying data from a MySQL database in PHP using timestamps and averages, it is important to properly format the timestamps and calculate averages before displaying the data. This can be achieved by using PHP functions to manipulate the timestamps and calculate averages from the database query results. Additionally, consider using loops or arrays to iterate through the data and display it in a user-friendly format.

// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

// Query to retrieve data from MySQL database
$sql = "SELECT timestamp, value FROM table";
$result = $conn->query($sql);

// Calculate average value
$total = 0;
$count = 0;

while($row = $result->fetch_assoc()) {
    $total += $row['value'];
    $count++;
}

$average = $total / $count;

// Display data with formatted timestamps and average
echo "<table>";
echo "<tr><th>Timestamp</th><th>Value</th></tr>";

$result = $conn->query($sql);

while($row = $result->fetch_assoc()) {
    $timestamp = date('Y-m-d H:i:s', strtotime($row['timestamp']));
    echo "<tr><td>$timestamp</td><td>{$row['value']}</td></tr>";
}

echo "</table>";
echo "Average value: $average";