SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Quake 1 Addict CreedFeed's Avatar
    Join Date
    Feb 2002
    Location
    Milwaukee, WI
    Posts
    296
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How To Add Minutes/Seconds To Calculate Total Time

    I've got a varchar column in my database to hold the length of a song... i.e. 5:35 would be 5 minutes and 35 seconds. What I want to do is add up the lengths of songs and display the total length of all songs. How would I do this?
    -- Steve Caponetto
    Quake 1 Resurrection :: CreedFeed

  2. #2
    SitePoint Wizard johnn's Avatar
    Join Date
    Mar 2001
    Location
    Southern California, USA
    Posts
    1,181
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if $db_field is 5:35 as you said, then
    PHP Code:
    $time_part explode(":",$db_field);
    $minutes   = (int) $time_part[0];
    $seconds   = (int) $time_part[1]; 

  3. #3
    SitePoint Wizard Chris82's Avatar
    Join Date
    Mar 2002
    Location
    Osnabrück
    Posts
    1,003
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The way you have the length of every song stored in the db is IMO not such a good idea.
    In order to calculate the total length of all songs (if this is what you want) you would need to select all fields and do the calculation with PHP.

    like:

    PHP Code:
    $minutes 0;
    $seconds 0;
    while (
    $data mysql_fetch_row($query))
    {
       
    extract($data);
       
    $time explode($colwithtime);
       
    $minutes += $time[0];
       
    $seconds += $time[1];

    I would suggest you store the the length of a song as seconds in an integer field.

    min * 60 + sec

    then you can use:

    PHP Code:
    $query mysql_query("SELECT SUM(songlength) AS slength");
    $length mysql_result($query0);

    $minutes = (int)$length 60;
    $seconds = (int)$length 60
    This is IMO better.

  4. #4
    Quake 1 Addict CreedFeed's Avatar
    Join Date
    Feb 2002
    Location
    Milwaukee, WI
    Posts
    296
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    HEre's what I did:

    PHP Code:
    $time_part explode(":",$song_length);
    $minutes   = (int) $time_part[0];
    $seconds   = (int) $time_part[1];
            
    $total_minutes $total_minutes $minutes;
    $total_seconds $total_seconds $seconds;
            
    $total_minutes = (int) $total_minutes + (int) ($total_seconds 60);
    $total_seconds $total_seconds 60;

    if((int) 
    $total_seconds <= 9) { $total_seconds '0'.$total_seconds; }
    $total_length $total_minutes.':'.$total_seconds
    You are right though... it seems storing the time as seconds would be much easier. I think I'll change that now. Thanks!
    -- Steve Caponetto
    Quake 1 Resurrection :: CreedFeed


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •