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

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.