What is the best way to calculate the difference between two times stored in a MySQL database in PHP?

To calculate the difference between two times stored in a MySQL database in PHP, you can use the DateTime class to create DateTime objects for each time, and then use the diff() method to calculate the difference between them. This will give you a DateInterval object which you can then extract the time difference from.

// Connect to MySQL database
$pdo = new PDO("mysql:host=localhost;dbname=database_name", "username", "password");

// Retrieve the two times from the database
$stmt = $pdo->prepare("SELECT time1, time2 FROM table_name WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch();

// Create DateTime objects for the two times
$time1 = new DateTime($row['time1']);
$time2 = new DateTime($row['time2']);

// Calculate the difference between the two times
$interval = $time1->diff($time2);

// Output the time difference
echo $interval->format('%H hours, %i minutes, %s seconds');