• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3374
  • Last Modified:

Getting Last Record From a MySQL Query

How do you find out what the last record in a mysql table is?

I tried having it do a mysql_num_rows and then seeing if the ID is greater than the total but that does not work because some of my entries in my table have an id of say...503 but there's only 200 total rows.

I need to be able to know if the current selected row is the LAST record in the database so that I know whether not the NEXT id should be the FIRST id...and that leads me to another question...how would I tell what the FIRST id is for the first row in the table?

If you need further clarification please let me know.

Jeff Long
Jeff Long
1 Solution
Matthew KellyCommented:
Does the below example help any?

You should be able to tell by the index location the result being displayed is using: http://www.php.net/mysql_result

If this is not what you are looking for please explain your query/code farther.
$sql = "SELECT * FROM tbl";
$result = mysql_query($sql);
echo "First record: ".mysql_result($result,0,"col_name");
echo "Last record: ".mysql_result($result,mysql_num_rows($result)-1,"col_name");
for ( $i=0; $i<mysql_num_rows($result);$i++ )
if ( $i==0 ) { echo "First record: ".mysql_result($result,$i,"col_name"); }
else if ( $i=(mysql_num_rows($result)-1) ) { echo "Last record: ".mysql_result($result,$i,"col_name"); }
else { echo "Middle record number ".$i.": ".mysql_result($result,$i,"col_name"); }

Open in new window

Jeff LongEntrepreneur Author Commented:
Nah I figured it out but thanks.  You're doing it waaay to complicated ;-)

It's as simple as doing a query and displaying the records using ASC to get the FIRST entry and DESC to get the LAST ;-)
Roger BaklundCommented:
An even simpler solution:
select min(id) from mytable
select max(id) from mytable

Open in new window

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Roger BaklundCommented:
...you could even combine these in the same query:
select min(id) as smallest,max(id) as largest from mytable

Open in new window

Hi there, well with this function you can get it, and for instance: i am saving it into a ssession variable, the function must be placed after the mysql_query, about the first record you already answered, Xd, cheers!
query code
$Result1 = mysql_query($insertSQL, $ConextoDB) or die(mysql_error());

Open in new window

PAQed with points refunded (500)

EE Admin

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now