Forum Moderators: coopster

Message Too Old, No Replies

mysql_fetch_array compare data to previous row

         

jackvull

11:04 am on Jun 13, 2006 (gmt 0)

10+ Year Member



Hi
I have some code where I retrieve data from a database with various joins. Some of this data has a link to an image but the data is repeated several times due to the joins.
What i want to do is loop through the data but only print out the image if some other data in the row is different to the row before.
For example I display the following:
Image1
Artist Name1
Artist Name1
Artist Name1

Now if on the next row the Artist Name changes, I would like to put in another Image so:
Image1
Artist Name1
Artist Name1
Artist Name1
Image2
Artist Name2
Artist Name2
Artist Name2

However, I don't know how to compare the row with Artist 2 to the previous row using mysql_fetch_array.

My code is below:

$loopct = 0;
while ($rowAlbums = mysql_fetch_array($detailsAlbums, MYSQL_BOTH))
{
if ($loopct == 0)
{
echo "<tr><td><img src='".$rowAlbums['PicturePath']."'></td><td colspan = '6'>".$rowAlbums['Artist']." - ".$rowAlbums['Title'].";
}
//etc. listing the rest of the details

MattAU

12:18 am on Jun 14, 2006 (gmt 0)

10+ Year Member



You could do something like this:

$loopct = 0;
while ($rowAlbums = mysql_fetch_array($detailsAlbums, MYSQL_BOTH))
{
if ($loopct == 0)
{
echo "<tr><td><img src='".$rowAlbums['PicturePath']."'></td><td colspan = '6'>".$rowAlbums['Artist']." - ".$rowAlbums['Title'].";
$last_artist = $rowAlbums['Artist'];
$loopct++;
}
elseif($rowAlbums['Artist']!= $last_artist)
{
//echo img etc.
$last_artist = $rowAlbums['Artist'];
}
else
{
//No img, just artist name
$last_artist = $rowAlbums['Artist'];
}
}

Note that this will only work if you're looking at just the previous artist. If you want to check whether the artist has been displayed at all, add the names to an array and do an array_search instead of elseif($rowAlbums['Artist']!= $last_artist).

jackvull

9:06 am on Jun 14, 2006 (gmt 0)

10+ Year Member



Thanks for that idea. I'll give it a go.
Out of interest, as the resultset is already ni an array, how costly would it be to move the data pointer each time using mysql_data_seek fetch a row, then move the pointer back forward, getch the current row and carry on looping?

MattAU

9:33 pm on Jun 14, 2006 (gmt 0)

10+ Year Member



It would take a bit longer, seeing as you need to move backward and forwards, and use mysql_fetch_array for each row twice. If you've only got 10 rows with a couple of values, the difference will be pretty negligible.