DIM3NSION Posted April 19, 2012 Share Posted April 19, 2012 I want to loop through a MySQL table, and perform a calculation based on the current row the loop is on and the previous loop. Say my table has 2 columns - Film_id and FilmRelease, how would I loop through and echo out a calculation of the current FilmRelease and the previous row's column value? Thanks guys I have got to this stage, but for some reason it's not printing out anything <?php mysql_connect("localhost", "****", "*****") or die(mysql_error()); mysql_select_db("*****") or die(mysql_error()); $sql = mysql_query("SELECT FilmRelease FROM Films_Info") or die(mysql_error()); $last_value = null; while ($row = mysql_fetch_assoc($sql)) { if (!is_null($last_value)) { print date_diff($row['FilmRelease'], $last_value) . "<BR>"; } $last_value = $row['FilmRelease']; } Link to comment https://forums.phpfreaks.com/topic/261241-loop-through-mysql-table-and-perform-action-on-row-and-previous-row-field-php/ Share on other sites More sharing options...
silkfire Posted April 19, 2012 Share Posted April 19, 2012 You can JOIN a table on itself with previous id as a joiner. You must use RIGHT join to not drop the first NULL record. The two columns I select here are the ones I compare. Very important to not forget to ALIAS the columns to prevent name collision. SELECT `Films_Info`.`FilmRelease` AS `FilmRelease1`, `previous`.`FilmRelease` AS `FilmRelease2` FROM `Films_Info` AS `previous` RIGHT JOIN `Films_Info` ON (`previous`.id = `Films_Info`.id - 1) Link to comment https://forums.phpfreaks.com/topic/261241-loop-through-mysql-table-and-perform-action-on-row-and-previous-row-field-php/#findComment-1338723 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.