我如何在PHP中的状态更改之间进行计时?

When the status changes to prepare/preparing, the timer begins. I then want to stop the timer and calculate the difference when the status changes to ready, and store it as time in the database. Ive tried various ways but can't seem to get it working, what am I doing wrong? Thanks

if(isset($_POST['prepare'])){
        $_SESSION['startTime'] = time();
        $question2="UPDATE `order` SET orderStatus='Preparing', idEmployee='$_SESSION[id]' WHERE idorder='$_POST[id]'";
        $sth = $db->prepare($question2);
        $sth->execute();
    }

    if(isset($_POST['ready'])){
        $total = time() - $_SESSION['startTime'];
        echo date('h:i:s', $total);

        $question2="UPDATE `order` SET orderStatus='Completed', timeCompleted='$total' WHERE idorder='$_POST[id]'";
        $sth = $db->prepare($question2);
        $sth->execute();
    }

edit: I overcame the issues I was having by simply using a method within the DateTime class. I began by recording the time from when the order was taken, I also recorded the time of when the order was completed. I then used the method diff() to calculate the difference between the 2 recorded times and stored the results in my db.

if(isset($_POST['prepare'])){
        $_SESSION['startTime'] = new DateTime();
        $question2="UPDATE `order` SET orderStatus='Preparing', idEmployee='$_SESSION[id]' WHERE idorder='$_POST[prepare]'";
        $sth = $db->prepare($question2);
        $sth->execute();
}

if(isset($_POST['ready'])){
        $endTime = new DateTime();
        $i = $_SESSION['startTime']->diff($endTime);
        $end = $i->format('%h:%i:%s');

        $question2="UPDATE `order` SET orderStatus='Completed', timeCompleted='$end' WHERE idorder='$_POST[ready]'";
        $sth = $db->prepare($question2);
        $sth->execute();
}

Replace $total = time() - $_SESSION['startTime'] with $total = time() - strtotime($_SESSION['startTime'])

And add session_start(); to the top of your code if you didn't

Then it will work.

If both prepare and ready are actioned on the same machine by the same person (within the same session) - this code should work. If you believe all this to be true - I would check to make sure the session variables are being set print_r($_SESSION)

However, I would recommend when you update orderStatus to 'Preparing', creating a new column called timeStarted and update that to time(), then when you are updating to 'Completed' set timecompleted also to time()

You can then easily work out the difference, as currently (if this code did work timeCompleted is actually timeTaken) - for which you could even add a 3rd column which is the difference between the two for easy reporting.

Doing it this way means if it takes longer than the session or the computer restarts / re login the startTime is not lost