PDA

View Full Version : Finding the last column in table


duniyadnd
01-06-2003, 11:07 PM
Is there any way I can find the last element of a table in a certain column besides using a while loop to go through till I reach the last element.

If its the while loop, i presume its this:

while ($row = mysql_fetch_object($Query))
{
$length = $row->id;
}

However, I want to avoid using this, because I can only call the Query once it seems, everytime I use a while loop. I also tried to use the "end" function in PhP, but no such luck, I get the last column, last element.

I couldn't figure out if this was a php problem or sql problem as I can't figure out a way of getting this in SQL and tried various methods in PhP.

-------------------------------------------------------------
Uhhhhh... yeah.. sorry moderators, wrong forum, can't figure out a way to delete -> forward to SQL please
--------------------------------------------------------------

Thanks
Duniyadnd

WA
01-07-2003, 01:24 AM
There are a couple of ways I can think of, depending on at what point you need to know the ID of the last row in your table:

1) If you need to know immediately after inserting the last row, use mysql_insert_id . More info here: http://www.php.net/manual/en/function.mysql-insert-id.php

2) If you need to know at any point in time, a technique that should work is:

$myids=mysql_query("SELECT id from mytable");
$countids=mysql_num_rows($myids);
$lastid=mysql_result($myids, $countids);

The above should be fairly self explanatory, though I have yet to actually test it out. It should work in returning the ID of the last row in your table.

Spookster
01-07-2003, 04:30 AM
Or if you had a auto-increment field or some other kind of incrementing field then:

SELECT MAX(incrementingfieldname), fieldyouwant FROM tablename LIMIT 1;

duniyadnd
01-07-2003, 02:31 PM
Thanks for the help so far ppl..

Yeah, I thought of something like that Spookster, but does this problem arise that in the autoincrementing column, there are a few cells missing.

ie. Instead of 1,2,3,4,5,6,7,8,.... n;

we have 1,2,3,4,7,8,...n;

meaning we actually have n-2 cells, but i want the value of "n".

Duniyadnd

Spookster
01-07-2003, 03:52 PM
Doesn't matter.

the max of 1,2,3,4,5,6,7,8 is 8

the max of 1,3,8 is 8