Jump to content

Loop through MYSQL table and perform action on row and previous row field PHP


DIM3NSION

Recommended Posts

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

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)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.