简体   繁体   中英

How to calculate time difference for multiple rows with same id and sum them up to give total time used?

I have a database and a table with three columns, username, and timein and timeout.

I have more than 100 users and Every user have multiple rows in the table with different time intervals.

Now I can calculate the time difference in min using the below code, but i have no idea how to calculate the sum off all time differences.

    Eg. of DB :

        **ID     a_id              o_t                    c_t                  date**
          1     user_1     Sep-19,2019 10:03:32    Sep-19,2019 10:03:32      Sep-19,2019
          2     user_2     Sep-19,2019 10:05:32    Sep-19,2019 10:06:32      Sep-19,2019
          3     user_3     Sep-19,2019 10:06:32    Sep-19,2019 10:09:32      Sep-19,2019
          4     user_1     Sep-19,2019 10:07:32    Sep-19,2019 10:08:32      Sep-19,2019
          5     user_2     Sep-19,2019 10:09:32    Sep-19,2019 10:12:32      Sep-19,2019



    <?php 
           $sql = "SELECT DIStINCT(a_id) FROM eu_edits";
           $result = $conn->query($sql);
           if ($result->num_rows > 0) {   
           while($row = $result->fetch_assoc()) {   
                $a_id = $row["a_id"];
    ?>

        <?php 
              $sql2 = "SELECT * FROM eu_edits WHERE date = '$date2' AND a_id = '$a_id'";
              $result2 = $conn->query($sql2);
              if ($result2->num_rows > 0) {   
              while($row2 = $result2->fetch_assoc()) { 
                 $o_t = $row2["o_t"];
                  $c_t = $row2["c_t"];

           $to_time = strtotime($o_t);
           $from_time = strtotime($c_t);
           $time = round(abs($to_time - $from_time) / 60,2). " minute";

      ?>

  <tr>
    <td> <?php echo $a_id; ?> </td>   
    <td> <?php echo $time; ?> </td>
    <td> <?php echo $date; ?> </td>
  </tr>


<?php 

        } } else { }

         } } else { }

        ?>

Any Help is appreciated.,.

Add variable sum in the loop like

<?php 
              $sql2 = "SELECT * FROM eu_edits WHERE date = '$date2' AND a_id = '$a_id'";
              $result2 = $conn->query($sql2);
             $sum=0;
              if ($result2->num_rows > 0) {   
              while($row2 = $result2->fetch_assoc()) { 
                 $o_t = $row2["o_t"];
                  $c_t = $row2["c_t"];

           $to_time = strtotime($o_t);
           $from_time = strtotime($c_t);
           $sum=$sum+$time; // This will sum all your time differences
           $time = round(abs($to_time - $from_time) / 60,2). " minute";

        }}
      ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM