How can PHP be utilized to sum up time intervals stored in a database table and display the total duration?
To sum up time intervals stored in a database table and display the total duration, you can fetch the time intervals from the database, convert them to seconds, sum them up, and then convert the total back to a readable format (e.g., hours:minutes:seconds).
// Connect to your database
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");
// Fetch time intervals from the database
$stmt = $pdo->query("SELECT time_interval FROM your_table");
$totalSeconds = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// Convert time interval to seconds
list($hours, $minutes, $seconds) = explode(':', $row['time_interval']);
$totalSeconds += $hours * 3600 + $minutes * 60 + $seconds;
}
// Convert total seconds to hours:minutes:seconds format
$totalDuration = gmdate("H:i:s", $totalSeconds);
// Display the total duration
echo "Total Duration: " . $totalDuration;
Keywords
Related Questions
- What potential pitfalls can arise from using the "AND" operator in the SQL query construction in PHP?
- How does the process of token generation and validation work in PHP sessions to prevent session hijacking?
- What is the difference between using a for loop and a while loop in PHP for distributing images into multiple columns?