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?
| SitePoint Sponsor |


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?





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];





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:
I would suggest you store the the length of a song as seconds in an integer field.PHP Code:$minutes = 0;
$seconds = 0;
while ($data = mysql_fetch_row($query))
{
extract($data);
$time = explode($colwithtime);
$minutes += $time[0];
$seconds += $time[1];
}
min * 60 + sec
then you can use:
This is IMO better.PHP Code:$query = mysql_query("SELECT SUM(songlength) AS slength");
$length = mysql_result($query, 0);
$minutes = (int)$length / 60;
$seconds = (int)$length % 60;


HEre's what I did:
You are right though... it seems storing the time as seconds would be much easier. I think I'll change that now. Thanks!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;
Bookmarks