Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

geting the second to last result from a loop 1

Status
Not open for further replies.

pushyr

Programmer
Jul 2, 2007
159
GB
Hi,

I've got a while loop like this....

Code:
while ($queryTable01 = mysql_fetch_array($queryTable00)) { 

}

if the result is something like this...

1
2
3
4
5
6

how would i get the second to last result being... '5' ?

 
? Put a counter variable in the loop, then subtract 1 from its final value?

If you want the best response to a question, please check out FAQ222-2244 first.
'If we're supposed to work in Hex, why have we only got A fingers?'
Drive a Steam Roller
 
sorry to be a thicko... but how would i do that?
 
That can't be sensible. Don't grab the whole recordset and traverse in php just to get a single result from an arbitrary row. Use indices and where clauses to reduce the recordset.
Or add this to the end of the query you use.
Code:
 limit 1 offset 1
and then add an order by clause that reverses the order.
 
hey jpadie.. i cant update the query... as i need the last two rows in the result (in addition to all the rows in the result)

both 6 and 5... my intention is to do an equation with these two numbers

i can currently get the 6, but now i need to get the 5
 
You are already getting all the rows, so the easiest would be to store them somewhere so you can use them.

Code:
while ($queryTable01 = mysql_fetch_array($queryTable00)) { 
$myRows[]=$queryTable01;
...


}


$lastRow=$myRows[count($myRows)-1];
$secondtolastRow=$myRows[count($myRows)-2];

You could of course also use the mysql_data_seek function to move the result pointer one row back to get the second to last row.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Or you could add desc to the query (so your last values come first) or keep a rolling 2 element array and shift values into it as you go.
I know you got it working but I like to contribute!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top