How can i calculate the time user is spending on page?

I have made a function , on login the user actual date month-day-year hours-minutes-second are saved on database .
On log-out i have made a function to calculate the time the user has stayed on page but for some reasons the function is not working.
I need to calculate with the following idea , ‘The time user has logged out’ – ‘The time user has been logged in ‘=’total’,
Then i need to get the all total the user has spent on page and add this total i made the calculation.

 [![public function calculateTimeOnPage(){

        $id = $_SESSION['userid'];
        $stmt = $this->connection->pdo->prepare("SELECT * FROM users WHERE id = '$id'");
        
        $stmt->execute();    
        $result = $stmt->fetch();
        $end_time_on_page = Date("Y-m-d H:i:s");
        $todayDate_ = date('Y-m-d H:i:s');
     
        $total = strtotime($end_time_on_page) - strtotime($result['page_start_time']); 
  
        $actual_date = date("Y-m-d H:i:s",$result['time_on_page']);
    
        $calculate_time_on_page = $total + strtotime($actual_date);
        
        $data = date("Y-m-d H:i:s",$calculate_time_on_page);
        
        echo 'Data : '.$data . '<br>';
        
        $stmt_up = $this->connection->pdo->prepare("UPDATE users SET 
        time_on_page = TIMESTAMPDIFF(SECOND,'".$data."','".$todayDate_."')
        WHERE id = '$id'");

        function convertSecToTime($sec)
        {
            $date1 = new DateTime("@0");
            $date2 = new DateTime("@$sec");
            $interval = date_diff($date1, $date2);
            $parts = ['years' => 'y', 'months' => 'm', 'days' => 'd', 'hours' => 'h', 'minutes' => 'i', 'seconds' => 's'];
            $formatted = [];
            foreach($parts as $i => $part)
            {
                $value = $interval->$part;
                if ($value !== 0)
                {
                    if ($value == 1){
                        $i = substr($i, 0, -1);
                    }
                    $formatted[] = "$value $i";
                }
            }

            if (count($formatted) == 1)
            {
                return $formatted[0];
            }
            else
            {
                $str = implode(', ', array_slice($formatted, 0, -1));
                $str.= ' and ' . $formatted[count($formatted) - 1];
                return $str;
            }
        }

        //convertSecToTime($sec);

        echo convertSecToTime($result['time_on_page']); // qekjo perdoret per mi show sa kohe ka

        echo "UPDATE users SET 
        time_on_page = TIMESTAMPDIFF(SECOND,'".$data."','".$todayDate_."')
        WHERE id = '$id'";

        $stmt_up->execute();
    }][1]][1]